Skip to content

Commit 77ab9b0

Browse files
committed
PYTHON-2504 Run 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 bson/*.py pymongo/*.py gridfs/*.py test/*.py test/*/*.py
1 parent 475a2b6 commit 77ab9b0

File tree

117 files changed

+594
-552
lines changed

Some content is hidden

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

117 files changed

+594
-552
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: 2 additions & 3 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
@@ -360,5 +359,5 @@ def __hash__(self) -> int:
360359
def __ne__(self, other: Any) -> bool:
361360
return not self == other
362361

363-
def __repr__(self):
362+
def __repr__(self) -> str:
364363
return f"Binary({bytes.__repr__(self)}, {self.__subtype})"

bson/code.py

Lines changed: 2 additions & 3 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
@@ -87,7 +86,7 @@ def scope(self) -> Optional[Mapping[str, Any]]:
8786
"""Scope dictionary for this instance or ``None``."""
8887
return self.__scope
8988

90-
def __repr__(self):
89+
def __repr__(self) -> str:
9190
return f"Code({str.__repr__(self)}, {self.__scope!r})"
9291

9392
def __eq__(self, other: Any) -> bool:

bson/codec_options.py

Lines changed: 8 additions & 16 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,11 +168,11 @@ 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

182-
def __repr__(self):
175+
def __repr__(self) -> str:
183176
return "{}(type_codecs={!r}, fallback_encoder={!r})".format(
184177
self.__class__.__name__,
185178
self.__type_codecs,
@@ -293,7 +286,7 @@ def _replace(self, **kwargs: Any) -> "CodecOptions[_DocumentType]":
293286
class CodecOptions(_BaseCodecOptions):
294287
"""Encapsulates options used encoding and / or decoding BSON."""
295288

296-
def __init__(self, *args, **kwargs):
289+
def __init__(self, *args, **kwargs) -> None:
297290
"""Encapsulates options used encoding and / or decoding BSON.
298291
299292
The `document_class` option is used to define a custom type for use
@@ -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,
@@ -473,7 +465,7 @@ def _options_dict(self) -> Dict[str, Any]:
473465
"datetime_conversion": self.datetime_conversion,
474466
}
475467

476-
def __repr__(self):
468+
def __repr__(self) -> str:
477469
return f"{self.__class__.__name__}({self._arguments_repr()})"
478470

479471
def with_options(self, **kwargs: Any) -> "CodecOptions":

bson/datetime_ms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class DatetimeMS:
3434

3535
__slots__ = ("_value",)
3636

37-
def __init__(self, value: Union[int, datetime.datetime]):
37+
def __init__(self, value: Union[int, datetime.datetime]) -> None:
3838
"""Represents a BSON UTC datetime.
3939
4040
BSON UTC datetimes are defined as an int64 of milliseconds since the

bson/dbref.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def as_doc(self) -> SON[str, Any]:
101101
doc.update(self.__kwargs)
102102
return doc
103103

104-
def __repr__(self):
104+
def __repr__(self) -> str:
105105
extra = "".join([f", {k}={v!r}" for k, v in self.__kwargs.items()])
106106
if self.database is None:
107107
return f"DBRef({self.collection!r}, {self.id!r}{extra})"

bson/decimal128.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def __str__(self) -> str:
296296
return "NaN"
297297
return str(dec)
298298

299-
def __repr__(self):
299+
def __repr__(self) -> str:
300300
return f"Decimal128('{str(self)}')"
301301

302302
def __setstate__(self, value: Tuple[int, int]) -> None:

bson/json_util.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ class JSONOptions(CodecOptions):
224224
datetime_representation: int
225225
strict_uuid: bool
226226

227-
def __init__(self, *args, **kwargs):
227+
def __init__(self, *args, **kwargs) -> None:
228228
"""Encapsulates JSON options for :func:`dumps` and :func:`loads`.
229229
230230
:Parameters:
@@ -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: 2 additions & 3 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

@@ -51,5 +50,5 @@ def __ge__(self, dummy: Any) -> bool:
5150
def __gt__(self, other: Any) -> bool:
5251
return not isinstance(other, MaxKey)
5352

54-
def __repr__(self):
53+
def __repr__(self) -> str:
5554
return "MaxKey()"

bson/min_key.py

Lines changed: 2 additions & 3 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

@@ -51,5 +50,5 @@ def __ge__(self, other: Any) -> bool:
5150
def __gt__(self, dummy: Any) -> bool:
5251
return False
5352

54-
def __repr__(self):
53+
def __repr__(self) -> str:
5554
return "MinKey()"

bson/objectid.py

Lines changed: 4 additions & 6 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):
@@ -246,7 +244,7 @@ def __setstate__(self, value: Any) -> None:
246244
def __str__(self) -> str:
247245
return binascii.hexlify(self.__id).decode()
248246

249-
def __repr__(self):
247+
def __repr__(self) -> str:
250248
return f"ObjectId('{str(self)}')"
251249

252250
def __eq__(self, other: Any) -> bool:

bson/raw_bson.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,8 @@
5454
from typing import Any, ItemsView, Iterator, Mapping, Optional
5555

5656
from bson import _get_object_size, _raw_to_dict
57-
from bson.codec_options import _RAW_BSON_DOCUMENT_MARKER
57+
from bson.codec_options import _RAW_BSON_DOCUMENT_MARKER, CodecOptions
5858
from bson.codec_options import DEFAULT_CODEC_OPTIONS as DEFAULT
59-
from bson.codec_options import CodecOptions
6059
from bson.son import SON
6160

6261

@@ -131,7 +130,7 @@ class from the standard library so it can be used like a read-only
131130
elif not issubclass(codec_options.document_class, RawBSONDocument):
132131
raise TypeError(
133132
"RawBSONDocument cannot use CodecOptions with document "
134-
"class %s" % (codec_options.document_class,)
133+
"class {}".format(codec_options.document_class)
135134
)
136135
self.__codec_options = codec_options
137136
# Validate the bson object size.
@@ -173,7 +172,7 @@ def __eq__(self, other: Any) -> bool:
173172
return self.__raw == other.raw
174173
return NotImplemented
175174

176-
def __repr__(self):
175+
def __repr__(self) -> str:
177176
return "{}({!r}, codec_options={!r})".format(
178177
self.__class__.__name__,
179178
self.raw,

bson/regex.py

Lines changed: 2 additions & 3 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
@@ -116,7 +115,7 @@ def __eq__(self, other: Any) -> bool:
116115
def __ne__(self, other: Any) -> bool:
117116
return not self == other
118117

119-
def __repr__(self):
118+
def __repr__(self) -> str:
120119
return f"Regex({self.pattern!r}, {self.flags!r})"
121120

122121
def try_compile(self) -> "Pattern[_T]":

bson/son.py

Lines changed: 3 additions & 2 deletions
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
@@ -70,7 +71,7 @@ def __new__(cls: Type["SON[_Key, _Value]"], *args: Any, **kwargs: Any) -> "SON[_
7071
instance.__keys = []
7172
return instance
7273

73-
def __repr__(self):
74+
def __repr__(self) -> str:
7475
result = []
7576
for key in self.__keys:
7677
result.append(f"({key!r}, {self[key]!r})")

bson/timestamp.py

Lines changed: 2 additions & 3 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
@@ -112,7 +111,7 @@ def __ge__(self, other: Any) -> bool:
112111
return (self.time, self.inc) >= (other.time, other.inc)
113112
return NotImplemented
114113

115-
def __repr__(self):
114+
def __repr__(self) -> str:
116115
return f"Timestamp({self.__time}, {self.__inc})"
117116

118117
def as_datetime(self) -> datetime.datetime:

0 commit comments

Comments
 (0)