Skip to content

Commit ccf4055

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 0d658b3 commit ccf4055

File tree

117 files changed

+593
-550
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

+593
-550
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
@@ -65,12 +65,10 @@ class TypeEncoder(abc.ABC):
6565
@_abstractproperty
6666
def python_type(self) -> Any:
6767
"""The Python type to be converted into something serializable."""
68-
pass
6968

7069
@abc.abstractmethod
7170
def transform_python(self, value: Any) -> Any:
7271
"""Convert the given Python object into something serializable."""
73-
pass
7472

7573

7674
class TypeDecoder(abc.ABC):
@@ -86,12 +84,10 @@ class TypeDecoder(abc.ABC):
8684
@_abstractproperty
8785
def bson_type(self) -> Any:
8886
"""The BSON type to be converted into our own type."""
89-
pass
9087

9188
@abc.abstractmethod
9289
def transform_bson(self, value: Any) -> Any:
9390
"""Convert the given BSON value into our own type."""
94-
pass
9591

9692

9793
class TypeCodec(TypeEncoder, TypeDecoder):
@@ -107,8 +103,6 @@ class TypeCodec(TypeEncoder, TypeDecoder):
107103
See :ref:`custom-type-type-codec` documentation for an example.
108104
"""
109105

110-
pass
111-
112106

113107
_Codec = Union[TypeEncoder, TypeDecoder, TypeCodec]
114108
_Fallback = Callable[[Any], Any]
@@ -167,8 +161,7 @@ def __init__(
167161
self._decoder_map[codec.bson_type] = codec.transform_bson
168162
if not is_valid_codec:
169163
raise TypeError(
170-
"Expected an instance of %s, %s, or %s, got %r instead"
171-
% (TypeEncoder.__name__, TypeDecoder.__name__, TypeCodec.__name__, codec)
164+
f"Expected an instance of {TypeEncoder.__name__}, {TypeDecoder.__name__}, or {TypeCodec.__name__}, got {codec!r} instead"
172165
)
173166

174167
def _validate_type_encoder(self, codec: _Codec) -> None:
@@ -178,11 +171,11 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
178171
if issubclass(cast(TypeCodec, codec).python_type, pytype):
179172
err_msg = (
180173
"TypeEncoders cannot change how built-in types are "
181-
"encoded (encoder %s transforms type %s)" % (codec, pytype)
174+
"encoded (encoder {} transforms type {})".format(codec, pytype)
182175
)
183176
raise TypeError(err_msg)
184177

185-
def __repr__(self):
178+
def __repr__(self) -> str:
186179
return "{}(type_codecs={!r}, fallback_encoder={!r})".format(
187180
self.__class__.__name__,
188181
self.__type_codecs,
@@ -247,7 +240,7 @@ class _BaseCodecOptions(NamedTuple):
247240
class CodecOptions(_BaseCodecOptions):
248241
"""Encapsulates options used encoding and / or decoding BSON."""
249242

250-
def __init__(self, *args, **kwargs):
243+
def __init__(self, *args, **kwargs) -> None:
251244
"""Encapsulates options used encoding and / or decoding BSON.
252245
253246
The `document_class` option is used to define a custom type for use
@@ -398,10 +391,9 @@ def _arguments_repr(self) -> str:
398391
)
399392

400393
return (
401-
"document_class=%s, tz_aware=%r, uuid_representation=%s, "
402-
"unicode_decode_error_handler=%r, tzinfo=%r, "
403-
"type_registry=%r, datetime_conversion=%s"
404-
% (
394+
"document_class={}, tz_aware={!r}, uuid_representation={}, "
395+
"unicode_decode_error_handler={!r}, tzinfo={!r}, "
396+
"type_registry={!r}, datetime_conversion={}".format(
405397
document_class_repr,
406398
self.tz_aware,
407399
uuid_rep_repr,
@@ -425,7 +417,7 @@ def _options_dict(self) -> Dict[str, Any]:
425417
"datetime_conversion": self.datetime_conversion,
426418
}
427419

428-
def __repr__(self):
420+
def __repr__(self) -> str:
429421
return f"{self.__class__.__name__}({self._arguments_repr()})"
430422

431423
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: 2 additions & 2 deletions
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.
@@ -173,7 +173,7 @@ def __eq__(self, other: Any) -> bool:
173173
return self.__raw == other.raw
174174
return NotImplemented
175175

176-
def __repr__(self):
176+
def __repr__(self) -> str:
177177
return "{}({!r}, codec_options={!r})".format(
178178
self.__class__.__name__,
179179
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:

gridfs/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
class GridFS:
5757
"""An instance of GridFS on top of a single Database."""
5858

59-
def __init__(self, database: Database, collection: str = "fs"):
59+
def __init__(self, database: Database, collection: str = "fs") -> None:
6060
"""Create a new instance of :class:`GridFS`.
6161
6262
Raises :class:`TypeError` if `database` is not an instance of
@@ -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

0 commit comments

Comments
 (0)