Skip to content

Commit 029bbe5

Browse files
committed
PEP8 / Pylint cleanups.
1 parent c0474a0 commit 029bbe5

File tree

6 files changed

+74
-61
lines changed

6 files changed

+74
-61
lines changed

pymongo/collection.py

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,19 @@
3737
from pymongo.message import _INSERT, _UPDATE, _DELETE
3838
from pymongo.options import ReturnDocument, _WriteOp
3939
from pymongo.read_preferences import ReadPreference
40-
from pymongo.results import *
40+
from pymongo.results import (BulkWriteResult,
41+
DeleteResult,
42+
InsertOneResult,
43+
InsertManyResult,
44+
UpdateResult)
4145
from pymongo.write_concern import WriteConcern
4246

4347

4448
try:
4549
from collections import OrderedDict
46-
ordered_types = (SON, OrderedDict)
50+
_ORDERED_TYPES = (SON, OrderedDict)
4751
except ImportError:
48-
ordered_types = SON
52+
_ORDERED_TYPES = (SON,)
4953

5054
_NO_OBJ_ERROR = "No matching object found"
5155

@@ -146,7 +150,7 @@ def __init__(self, database, name, create=False, codec_options=None,
146150
def _command(
147151
self, command, read_preference=None, codec_options=None, **kwargs):
148152
"""Internal command helper.
149-
153+
150154
:Parameters:
151155
- `command` - The command itself, as a SON instance.
152156
- `read_preference` (optional) - An subclass of
@@ -200,9 +204,8 @@ def __repr__(self):
200204

201205
def __eq__(self, other):
202206
if isinstance(other, Collection):
203-
us = (self.__database, self.__name)
204-
them = (other.__database, other.__name)
205-
return us == them
207+
return (self.__database == other.database and
208+
self.__name == other.name)
206209
return NotImplemented
207210

208211
def __ne__(self, other):
@@ -334,20 +337,24 @@ def _insert(self, docs, ordered=True,
334337

335338
if manipulate:
336339
def gen():
337-
db = self.__database
340+
"""Generator that applies SON manipulators to each document
341+
and adds _id if necessary.
342+
"""
343+
_db = self.__database
338344
for doc in docs:
339345
# Apply user-configured SON manipulators. This order of
340346
# operations is required for backwards compatibility,
341347
# see PYTHON-709.
342-
doc = db._apply_incoming_manipulators(doc, self)
348+
doc = _db._apply_incoming_manipulators(doc, self)
343349
if '_id' not in doc:
344350
doc['_id'] = ObjectId()
345351

346-
doc = db._apply_incoming_copying_manipulators(doc, self)
352+
doc = _db._apply_incoming_copying_manipulators(doc, self)
347353
ids.append(doc['_id'])
348354
yield doc
349355
else:
350356
def gen():
357+
"""Generator that only tracks existing _ids."""
351358
for doc in docs:
352359
ids.append(doc.get('_id'))
353360
yield doc
@@ -1312,8 +1319,8 @@ def aggregate(self, pipeline, **kwargs):
13121319
}
13131320
return CommandCursor(self, cursor_info, address)
13141321

1315-
# TODO key and condition ought to be optional, but deprecation
1316-
# could be painful as argument order would have to change.
1322+
# key and condition ought to be optional, but deprecation
1323+
# would be painful as argument order would have to change.
13171324
def group(self, key, condition, initial, reduce, finalize=None, **kwargs):
13181325
"""Perform a query similar to an SQL *group by* operation.
13191326
@@ -1747,10 +1754,10 @@ def find_and_modify(self, query={}, update=None,
17471754
", find_one_and_replace, or find_one_and_update instead",
17481755
DeprecationWarning, stacklevel=2)
17491756

1750-
if (not update and not kwargs.get('remove', None)):
1757+
if not update and not kwargs.get('remove', None):
17511758
raise ValueError("Must either update or remove")
17521759

1753-
if (update and kwargs.get('remove', None)):
1760+
if update and kwargs.get('remove', None):
17541761
raise ValueError("Can't do both update and remove")
17551762

17561763
# No need to include empty args
@@ -1766,16 +1773,16 @@ def find_and_modify(self, query={}, update=None,
17661773
kwargs['sort'] = helpers._index_document(sort)
17671774
# Accept OrderedDict, SON, and dict with len == 1 so we
17681775
# don't break existing code already using find_and_modify.
1769-
elif (isinstance(sort, ordered_types) or
1776+
elif (isinstance(sort, _ORDERED_TYPES) or
17701777
isinstance(sort, dict) and len(sort) == 1):
17711778
warnings.warn("Passing mapping types for `sort` is deprecated,"
17721779
" use a list of (key, direction) pairs instead",
17731780
DeprecationWarning, stacklevel=2)
17741781
kwargs['sort'] = sort
17751782
else:
17761783
raise TypeError("sort must be a list of (key, direction) "
1777-
"pairs, a dict of len 1, or an instance of "
1778-
"SON or OrderedDict")
1784+
"pairs, a dict of len 1, or an instance of "
1785+
"SON or OrderedDict")
17791786

17801787

17811788
fields = kwargs.pop("fields", None)
@@ -1806,10 +1813,10 @@ def find_and_modify(self, query={}, update=None,
18061813
def __iter__(self):
18071814
return self
18081815

1809-
def next(self):
1816+
def __next__(self):
18101817
raise TypeError("'Collection' object is not iterable")
18111818

1812-
__next__ = next
1819+
next = __next__
18131820

18141821
def __call__(self, *args, **kwargs):
18151822
"""This is only here so that some API misusages are easier to debug.

pymongo/common.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,7 @@ def validate_auth_mechanism_properties(option, value):
298298

299299

300300
def validate_document_class(option, value):
301+
"""Validate the document_class option."""
301302
if not issubclass(value, collections.MutableMapping):
302303
raise ConfigurationError("%s must be a sublass of "
303304
"collections.MutableMapping" % (option,))

pymongo/cursor.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ def clone(self):
236236
return self._clone(True)
237237

238238
def _clone(self, deepcopy=True):
239+
"""Internal clone helper."""
239240
clone = self._clone_base()
240241
values_to_clone = ("spec", "projection", "skip", "limit",
241242
"max_time_ms", "comment", "max", "min",
@@ -800,7 +801,7 @@ def where(self, code):
800801
self.__spec["$where"] = code
801802
return self
802803

803-
def __send_message(self, message):
804+
def __send_message(self, msg):
804805
"""Send a query or getmore message and handles the response.
805806
806807
If message is ``None`` this is an exhaust cursor, which reads
@@ -811,7 +812,7 @@ def __send_message(self, message):
811812
"""
812813
client = self.__collection.database.connection
813814

814-
if message:
815+
if msg:
815816
kwargs = {
816817
"read_preference": self.__read_preference,
817818
"exhaust": self.__exhaust,
@@ -820,7 +821,7 @@ def __send_message(self, message):
820821
kwargs["address"] = self.__address
821822

822823
try:
823-
response = client._send_message_with_response(message, **kwargs)
824+
response = client._send_message_with_response(msg, **kwargs)
824825
self.__address = response.address
825826
if self.__exhaust:
826827
# 'response' is an ExhaustResponse.
@@ -873,7 +874,7 @@ def __send_message(self, message):
873874
self.__id = doc["cursor_id"]
874875

875876
# starting from doesn't get set on getmore's for tailable cursors
876-
if not (self.__query_flags & _QUERY_OPTIONS["tailable_cursor"]):
877+
if not self.__query_flags & _QUERY_OPTIONS["tailable_cursor"]:
877878
assert doc["starting_from"] == self.__retrieved, (
878879
"Result batch started from %s, expected %s" % (
879880
doc['starting_from'], self.__retrieved))
@@ -970,20 +971,20 @@ def address(self):
970971
def __iter__(self):
971972
return self
972973

973-
def next(self):
974+
def __next__(self):
974975
if self.__empty:
975976
raise StopIteration
976-
db = self.__collection.database
977+
_db = self.__collection.database
977978
if len(self.__data) or self._refresh():
978979
if self.__manipulate:
979-
return db._fix_outgoing(self.__data.popleft(),
980-
self.__collection)
980+
return _db._fix_outgoing(self.__data.popleft(),
981+
self.__collection)
981982
else:
982983
return self.__data.popleft()
983984
else:
984985
raise StopIteration
985986

986-
__next__ = next
987+
next = __next__
987988

988989
def __enter__(self):
989990
return self

pymongo/database.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ def add_son_manipulator(self, manipulator):
116116
"""
117117
base = SONManipulator()
118118
def method_overwritten(instance, method):
119+
"""Test if this method has been overridden."""
119120
return (getattr(
120121
instance, method).__func__ != getattr(base, method).__func__)
121122

@@ -188,9 +189,8 @@ def outgoing_copying_manipulators(self):
188189

189190
def __eq__(self, other):
190191
if isinstance(other, Database):
191-
us = (self.__connection, self.__name)
192-
them = (other.__connection, other.__name)
193-
return us == them
192+
return (self.__connection == other.connection and
193+
self.__name == other.name)
194194
return NotImplemented
195195

196196
def __ne__(self, other):
@@ -296,11 +296,13 @@ def create_collection(self, name, codec_options=None,
296296
read_preference, write_concern, **kwargs)
297297

298298
def _apply_incoming_manipulators(self, son, collection):
299+
"""Apply incoming manipulators to `son`."""
299300
for manipulator in self.__incoming_manipulators:
300301
son = manipulator.transform_incoming(son, collection)
301302
return son
302303

303304
def _apply_incoming_copying_manipulators(self, son, collection):
305+
"""Apply incoming copying manipulators to `son`."""
304306
for manipulator in self.__incoming_copying_manipulators:
305307
son = manipulator.transform_incoming(son, collection)
306308
return son
@@ -523,7 +525,7 @@ def validate_collection(self, name_or_collection,
523525
if "result" in res:
524526
info = res["result"]
525527
if (info.find("exception") != -1 or
526-
info.find("corrupt") != -1):
528+
info.find("corrupt") != -1):
527529
raise CollectionInvalid("%s invalid: "
528530
"%s" % (name, info))
529531
elif not res.get("valid", False):
@@ -694,12 +696,13 @@ def reset_error_history(self):
694696
def __iter__(self):
695697
return self
696698

697-
def next(self):
699+
def __next__(self):
698700
raise TypeError("'Database' object is not iterable")
699701

700-
__next__ = next
702+
next = __next__
701703

702704
def _default_role(self, read_only):
705+
"""Return the default user role for this database."""
703706
if self.name == "admin":
704707
if read_only:
705708
return "readAnyDatabase"
@@ -775,7 +778,7 @@ def _legacy_add_user(self, name, password, read_only, **kwargs):
775778
# First admin user add fails gle from mongos 2.0.x
776779
# and 2.2.x.
777780
elif (exc.details and
778-
'getlasterror' in exc.details.get('note', '')):
781+
'getlasterror' in exc.details.get('note', '')):
779782
pass
780783
else:
781784
raise

0 commit comments

Comments
 (0)