Skip to content

Commit efab0be

Browse files
committed
ruff --fix-only --select ALL --fixable ALL --target-version py37 --line-length=100 --unfixable COM812,D400,D415,ERA001,RUF100,SIM108,D211,D212,SIM105,SIM,PT,ANN204 bson/*.py pymongo/*.py gridfs/*.py test/*.py test/*/*.py
1 parent 475a2b6 commit efab0be

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

86 files changed

+396
-359
lines changed

bson/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ def get_data_and_view(data: Any) -> Tuple[Any, memoryview]:
237237
def _raise_unknown_type(element_type: int, element_name: str) -> NoReturn:
238238
"""Unknown type helper."""
239239
raise InvalidBSON(
240-
"Detected unknown BSON type %r for fieldname '%s'. Are "
241-
"you using the latest driver version?" % (chr(element_type).encode(), element_name)
240+
"Detected unknown BSON type {!r} for fieldname '{}'. Are "
241+
"you using the latest driver version?".format(chr(element_type).encode(), element_name)
242242
)
243243

244244

bson/_helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414

1515
"""Setstate and getstate functions for objects with __slots__, allowing
16-
compatibility with default pickling protocol
16+
compatibility with default pickling protocol
1717
"""
1818
from typing import Any, Mapping
1919

@@ -33,7 +33,7 @@ def _mangle_name(name: str, prefix: str) -> str:
3333

3434
def _getstate_slots(self: Any) -> Mapping[Any, Any]:
3535
prefix = self.__class__.__name__
36-
ret = dict()
36+
ret = {}
3737
for name in self.__slots__:
3838
mangled_name = _mangle_name(name, prefix)
3939
if hasattr(self, mangled_name):

bson/binary.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -330,8 +330,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
330330
return UUID(bytes=self)
331331

332332
raise ValueError(
333-
"cannot decode subtype %s to %s"
334-
% (self.subtype, UUID_REPRESENTATION_NAMES[uuid_representation])
333+
f"cannot decode subtype {self.subtype} to {UUID_REPRESENTATION_NAMES[uuid_representation]}"
335334
)
336335

337336
@property

bson/code.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Tools for representing JavaScript code in BSON.
16-
"""
15+
"""Tools for representing JavaScript code in BSON."""
1716

1817
from collections.abc import Mapping as _Mapping
1918
from typing import Any, Mapping, Optional, Type, Union

bson/codec_options.py

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,10 @@ class TypeEncoder(abc.ABC):
6363
@abc.abstractproperty
6464
def python_type(self) -> Any:
6565
"""The Python type to be converted into something serializable."""
66-
pass
6766

6867
@abc.abstractmethod
6968
def transform_python(self, value: Any) -> Any:
7069
"""Convert the given Python object into something serializable."""
71-
pass
7270

7371

7472
class TypeDecoder(abc.ABC):
@@ -84,12 +82,10 @@ class TypeDecoder(abc.ABC):
8482
@abc.abstractproperty
8583
def bson_type(self) -> Any:
8684
"""The BSON type to be converted into our own type."""
87-
pass
8885

8986
@abc.abstractmethod
9087
def transform_bson(self, value: Any) -> Any:
9188
"""Convert the given BSON value into our own type."""
92-
pass
9389

9490

9591
class TypeCodec(TypeEncoder, TypeDecoder):
@@ -105,8 +101,6 @@ class TypeCodec(TypeEncoder, TypeDecoder):
105101
See :ref:`custom-type-type-codec` documentation for an example.
106102
"""
107103

108-
pass
109-
110104

111105
_Codec = Union[TypeEncoder, TypeDecoder, TypeCodec]
112106
_Fallback = Callable[[Any], Any]
@@ -164,8 +158,7 @@ def __init__(
164158
self._decoder_map[codec.bson_type] = codec.transform_bson
165159
if not is_valid_codec:
166160
raise TypeError(
167-
"Expected an instance of %s, %s, or %s, got %r instead"
168-
% (TypeEncoder.__name__, TypeDecoder.__name__, TypeCodec.__name__, codec)
161+
f"Expected an instance of {TypeEncoder.__name__}, {TypeDecoder.__name__}, or {TypeCodec.__name__}, got {codec!r} instead"
169162
)
170163

171164
def _validate_type_encoder(self, codec: _Codec) -> None:
@@ -175,7 +168,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
175168
if issubclass(cast(TypeCodec, codec).python_type, pytype):
176169
err_msg = (
177170
"TypeEncoders cannot change how built-in types are "
178-
"encoded (encoder %s transforms type %s)" % (codec, pytype)
171+
"encoded (encoder {} transforms type {})".format(codec, pytype)
179172
)
180173
raise TypeError(err_msg)
181174

@@ -446,10 +439,9 @@ def _arguments_repr(self) -> str:
446439
)
447440

448441
return (
449-
"document_class=%s, tz_aware=%r, uuid_representation=%s, "
450-
"unicode_decode_error_handler=%r, tzinfo=%r, "
451-
"type_registry=%r, datetime_conversion=%s"
452-
% (
442+
"document_class={}, tz_aware={!r}, uuid_representation={}, "
443+
"unicode_decode_error_handler={!r}, tzinfo={!r}, "
444+
"type_registry={!r}, datetime_conversion={}".format(
453445
document_class_repr,
454446
self.tz_aware,
455447
uuid_rep_repr,

bson/json_util.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -350,10 +350,9 @@ def __new__(
350350

351351
def _arguments_repr(self) -> str:
352352
return (
353-
"strict_number_long=%r, "
354-
"datetime_representation=%r, "
355-
"strict_uuid=%r, json_mode=%r, %s"
356-
% (
353+
"strict_number_long={!r}, "
354+
"datetime_representation={!r}, "
355+
"strict_uuid={!r}, json_mode={!r}, {}".format(
357356
self.strict_number_long,
358357
self.datetime_representation,
359358
self.strict_uuid,
@@ -492,7 +491,7 @@ def _json_convert(obj: Any, json_options: JSONOptions = DEFAULT_JSON_OPTIONS) ->
492491
if hasattr(obj, "items"):
493492
return SON(((k, _json_convert(v, json_options)) for k, v in obj.items()))
494493
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
495-
return list(_json_convert(v, json_options) for v in obj)
494+
return [_json_convert(v, json_options) for v in obj]
496495
try:
497496
return default(obj, json_options)
498497
except TypeError:
@@ -720,7 +719,7 @@ def _parse_canonical_regex(doc: Any) -> Regex:
720719
if len(regex) != 2:
721720
raise TypeError(
722721
'Bad $regularExpression must include only "pattern"'
723-
'and "options" components: %s' % (doc,)
722+
'and "options" components: {}'.format(doc)
724723
)
725724
opts = regex["options"]
726725
if not isinstance(opts, str):

bson/max_key.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Representation for the MongoDB internal MaxKey type.
16-
"""
15+
"""Representation for the MongoDB internal MaxKey type."""
1716
from typing import Any
1817

1918

bson/min_key.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Representation for the MongoDB internal MinKey type.
16-
"""
15+
"""Representation for the MongoDB internal MinKey type."""
1716
from typing import Any
1817

1918

bson/objectid.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Tools for working with MongoDB ObjectIds.
16-
"""
15+
"""Tools for working with MongoDB ObjectIds."""
1716

1817
import binascii
1918
import calendar
@@ -166,7 +165,6 @@ def _random(cls) -> bytes:
166165

167166
def __generate(self) -> None:
168167
"""Generate a new value for this ObjectId."""
169-
170168
# 4 bytes current time
171169
oid = struct.pack(">I", int(time.time()))
172170

@@ -222,13 +220,13 @@ def generation_time(self) -> datetime.datetime:
222220
return datetime.datetime.fromtimestamp(timestamp, utc)
223221

224222
def __getstate__(self) -> bytes:
225-
"""return value of object for pickling.
223+
"""Return value of object for pickling.
226224
needed explicitly because __slots__() defined.
227225
"""
228226
return self.__id
229227

230228
def __setstate__(self, value: Any) -> None:
231-
"""explicit state set from pickling"""
229+
"""Explicit state set from pickling"""
232230
# Provide backwards compatability with OIDs
233231
# pickled with pymongo-1.9 or older.
234232
if isinstance(value, dict):

bson/raw_bson.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ class from the standard library so it can be used like a read-only
131131
elif not issubclass(codec_options.document_class, RawBSONDocument):
132132
raise TypeError(
133133
"RawBSONDocument cannot use CodecOptions with document "
134-
"class %s" % (codec_options.document_class,)
134+
"class {}".format(codec_options.document_class)
135135
)
136136
self.__codec_options = codec_options
137137
# Validate the bson object size.

bson/regex.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Tools for representing MongoDB regular expressions.
16-
"""
15+
"""Tools for representing MongoDB regular expressions."""
1716

1817
import re
1918
from typing import Any, Generic, Pattern, Type, TypeVar, Union

bson/son.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
1717
Regular dictionaries can be used instead of SON objects, but not when the order
1818
of keys is important. A SON object can be used just like a normal Python
19-
dictionary."""
19+
dictionary.
20+
"""
2021

2122
import copy
2223
import re

bson/timestamp.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Tools for representing MongoDB internal Timestamps.
16-
"""
15+
"""Tools for representing MongoDB internal Timestamps."""
1716

1817
import calendar
1918
import datetime

gridfs/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,6 @@ def put(self, data: Any, **kwargs: Any) -> Any:
141141
.. versionchanged:: 3.0
142142
w=0 writes to GridFS are now prohibited.
143143
"""
144-
145144
with GridIn(self.__collection, **kwargs) as grid_file:
146145
grid_file.write(data)
147146
return grid_file._id

pymongo/bulk.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,5 +509,6 @@ def execute(self, write_concern, session):
509509
if not write_concern.acknowledged:
510510
with client._socket_for_writes(session) as sock_info:
511511
self.execute_no_results(sock_info, generator, write_concern)
512+
return None
512513
else:
513514
return self.execute_command(generator, write_concern, session)

pymongo/change_stream.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,8 @@ def _aggregation_command_class(self):
156156
@property
157157
def _client(self):
158158
"""The client against which the aggregation commands for
159-
this ChangeStream will be run."""
159+
this ChangeStream will be run.
160+
"""
160161
raise NotImplementedError
161162

162163
def _change_stream_options(self):
@@ -221,7 +222,7 @@ def _process_result(self, result, sock_info):
221222
if self._start_at_operation_time is None:
222223
raise OperationFailure(
223224
"Expected field 'operationTime' missing from command "
224-
"response : %r" % (result,)
225+
"response : {!r}".format(result)
225226
)
226227

227228
def _run_aggregation_cmd(self, session, explicit_session):

pymongo/client_session.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -203,8 +203,9 @@ def __init__(
203203
if not isinstance(default_transaction_options, TransactionOptions):
204204
raise TypeError(
205205
"default_transaction_options must be an instance of "
206-
"pymongo.client_session.TransactionOptions, not: %r"
207-
% (default_transaction_options,)
206+
"pymongo.client_session.TransactionOptions, not: {!r}".format(
207+
default_transaction_options
208+
)
208209
)
209210
self._default_transaction_options = default_transaction_options
210211
self._snapshot = snapshot
@@ -275,25 +276,25 @@ def __init__(
275276
if not isinstance(read_concern, ReadConcern):
276277
raise TypeError(
277278
"read_concern must be an instance of "
278-
"pymongo.read_concern.ReadConcern, not: %r" % (read_concern,)
279+
"pymongo.read_concern.ReadConcern, not: {!r}".format(read_concern)
279280
)
280281
if write_concern is not None:
281282
if not isinstance(write_concern, WriteConcern):
282283
raise TypeError(
283284
"write_concern must be an instance of "
284-
"pymongo.write_concern.WriteConcern, not: %r" % (write_concern,)
285+
"pymongo.write_concern.WriteConcern, not: {!r}".format(write_concern)
285286
)
286287
if not write_concern.acknowledged:
287288
raise ConfigurationError(
288289
"transactions do not support unacknowledged write concern"
289-
": %r" % (write_concern,)
290+
": {!r}".format(write_concern)
290291
)
291292
if read_preference is not None:
292293
if not isinstance(read_preference, _ServerMode):
293294
raise TypeError(
294-
"%r is not valid for read_preference. See "
295+
"{!r} is not valid for read_preference. See "
295296
"pymongo.read_preferences for valid "
296-
"options." % (read_preference,)
297+
"options.".format(read_preference)
297298
)
298299
if max_commit_time_ms is not None:
299300
if not isinstance(max_commit_time_ms, int):
@@ -340,7 +341,7 @@ def _validate_session_write_concern(session, write_concern):
340341
else:
341342
raise ConfigurationError(
342343
"Explicit sessions are incompatible with "
343-
"unacknowledged write concern: %r" % (write_concern,)
344+
"unacknowledged write concern: {!r}".format(write_concern)
344345
)
345346
return session
346347

@@ -973,7 +974,7 @@ def _apply_to(self, command, is_retryable, read_preference, sock_info):
973974
if read_preference != ReadPreference.PRIMARY:
974975
raise InvalidOperation(
975976
"read preference in a transaction must be primary, not: "
976-
"%r" % (read_preference,)
977+
"{!r}".format(read_preference)
977978
)
978979

979980
if self._transaction.state == _TxnState.STARTING:

pymongo/collection.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ def __init__(
212212

213213
if not name or ".." in name:
214214
raise InvalidName("collection names cannot be empty")
215-
if "$" in name and not (name.startswith("oplog.$main") or name.startswith("$cmd")):
215+
if "$" in name and not (name.startswith(("oplog.$main", "$cmd"))):
216216
raise InvalidName("collection names must not contain '$': %r" % name)
217217
if name[0] == "." or name[-1] == ".":
218218
raise InvalidName("collection names must not start or end with '.': %r" % name)
@@ -336,8 +336,8 @@ def __getattr__(self, name: str) -> "Collection[_DocumentType]":
336336
if name.startswith("_"):
337337
full_name = f"{self.__name}.{name}"
338338
raise AttributeError(
339-
"Collection has no attribute %r. To access the %s"
340-
" collection, use database['%s']." % (name, full_name, full_name)
339+
"Collection has no attribute {!r}. To access the {}"
340+
" collection, use database['{}'].".format(name, full_name, full_name)
341341
)
342342
return self.__getitem__(name)
343343

@@ -569,6 +569,7 @@ def _insert_command(session, sock_info, retryable_write):
569569

570570
if not isinstance(doc, RawBSONDocument):
571571
return doc.get("_id")
572+
return None
572573

573574
def insert_one(
574575
self,
@@ -709,7 +710,7 @@ def gen():
709710

710711
write_concern = self._write_concern_for(session)
711712
blk = _Bulk(self, ordered, bypass_document_validation, comment=comment)
712-
blk.ops = [doc for doc in gen()]
713+
blk.ops = list(gen())
713714
blk.execute(write_concern, session=session)
714715
return InsertManyResult(inserted_ids, write_concern.acknowledged)
715716

@@ -2435,7 +2436,6 @@ def aggregate(
24352436
.. _aggregate command:
24362437
https://mongodb.com/docs/manual/reference/command/aggregate
24372438
"""
2438-
24392439
with self.__database.client._tmp_session(session, close=False) as s:
24402440
return self._aggregate(
24412441
_CollectionAggregationCommand,
@@ -2787,7 +2787,6 @@ def __find_and_modify(
27872787
**kwargs,
27882788
):
27892789
"""Internal findAndModify helper."""
2790-
27912790
common.validate_is_mapping("filter", filter)
27922791
if not isinstance(return_document, bool):
27932792
raise ValueError(

0 commit comments

Comments
 (0)