Skip to content

Commit 0092b0a

Browse files
authored
PYTHON-2504 Run pyupgrade 3.4.0 and ruff 0.0.265 (#1196)
pyupgrade --py37-plus bson/*.py pymongo/*.py gridfs/*.py test/*.py tools/*.py test/*/*.py 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,EM bson/*.py pymongo/*.py gridfs/*.py test/*.py test/*/*.py
1 parent afd7e1c commit 0092b0a

File tree

146 files changed

+1234
-1241
lines changed

Some content is hidden

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

146 files changed

+1234
-1241
lines changed

bson/__init__.py

+8-9
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

@@ -626,8 +626,7 @@ def gen_list_name() -> Generator[bytes, None, None]:
626626
The first 1000 keys are returned from a pre-built cache. All
627627
subsequent keys are generated on the fly.
628628
"""
629-
for name in _LIST_NAMES:
630-
yield name
629+
yield from _LIST_NAMES
631630

632631
counter = itertools.count(1000)
633632
while True:
@@ -942,18 +941,18 @@ def _name_value_to_bson(
942941
name, fallback_encoder(value), check_keys, opts, in_fallback_call=True
943942
)
944943

945-
raise InvalidDocument("cannot encode object: %r, of type: %r" % (value, type(value)))
944+
raise InvalidDocument(f"cannot encode object: {value!r}, of type: {type(value)!r}")
946945

947946

948947
def _element_to_bson(key: Any, value: Any, check_keys: bool, opts: CodecOptions) -> bytes:
949948
"""Encode a single key, value pair."""
950949
if not isinstance(key, str):
951-
raise InvalidDocument("documents must have only string keys, key was %r" % (key,))
950+
raise InvalidDocument(f"documents must have only string keys, key was {key!r}")
952951
if check_keys:
953952
if key.startswith("$"):
954-
raise InvalidDocument("key %r must not start with '$'" % (key,))
953+
raise InvalidDocument(f"key {key!r} must not start with '$'")
955954
if "." in key:
956-
raise InvalidDocument("key %r must not contain '.'" % (key,))
955+
raise InvalidDocument(f"key {key!r} must not contain '.'")
957956

958957
name = _make_name(key)
959958
return _name_value_to_bson(name, value, check_keys, opts)
@@ -971,7 +970,7 @@ def _dict_to_bson(doc: Any, check_keys: bool, opts: CodecOptions, top_level: boo
971970
if not top_level or key != "_id":
972971
elements.append(_element_to_bson(key, value, check_keys, opts))
973972
except AttributeError:
974-
raise TypeError("encoder expected a mapping type but got: %r" % (doc,))
973+
raise TypeError(f"encoder expected a mapping type but got: {doc!r}")
975974

976975
encoded = b"".join(elements)
977976
return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"

bson/_helpers.py

+2-2
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

+5-6
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
306306
.. versionadded:: 3.11
307307
"""
308308
if self.subtype not in ALL_UUID_SUBTYPES:
309-
raise ValueError("cannot decode subtype %s as a uuid" % (self.subtype,))
309+
raise ValueError(f"cannot decode subtype {self.subtype} as a uuid")
310310

311311
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
312312
raise ValueError(
@@ -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
@@ -341,7 +340,7 @@ def subtype(self) -> int:
341340

342341
def __getnewargs__(self) -> Tuple[bytes, int]: # type: ignore[override]
343342
# Work around http://bugs.python.org/issue7382
344-
data = super(Binary, self).__getnewargs__()[0]
343+
data = super().__getnewargs__()[0]
345344
if not isinstance(data, bytes):
346345
data = data.encode("latin-1")
347346
return data, self.__subtype
@@ -355,10 +354,10 @@ def __eq__(self, other: Any) -> bool:
355354
return False
356355

357356
def __hash__(self) -> int:
358-
return super(Binary, self).__hash__() ^ hash(self.__subtype)
357+
return super().__hash__() ^ hash(self.__subtype)
359358

360359
def __ne__(self, other: Any) -> bool:
361360
return not self == other
362361

363362
def __repr__(self):
364-
return "Binary(%s, %s)" % (bytes.__repr__(self), self.__subtype)
363+
return f"Binary({bytes.__repr__(self)}, {self.__subtype})"

bson/code.py

+3-4
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
@@ -54,7 +53,7 @@ def __new__(
5453
cls: Type["Code"],
5554
code: Union[str, "Code"],
5655
scope: Optional[Mapping[str, Any]] = None,
57-
**kwargs: Any
56+
**kwargs: Any,
5857
) -> "Code":
5958
if not isinstance(code, str):
6059
raise TypeError("code must be an instance of str")
@@ -88,7 +87,7 @@ def scope(self) -> Optional[Mapping[str, Any]]:
8887
return self.__scope
8988

9089
def __repr__(self):
91-
return "Code(%s, %r)" % (str.__repr__(self), self.__scope)
90+
return f"Code({str.__repr__(self)}, {self.__scope!r})"
9291

9392
def __eq__(self, other: Any) -> bool:
9493
if isinstance(other, Code):

bson/codec_options.py

+8-16
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,14 +101,12 @@ 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]
113107

114108

115-
class TypeRegistry(object):
109+
class TypeRegistry:
116110
"""Encapsulates type codecs used in encoding and / or decoding BSON, as
117111
well as the fallback encoder. Type registries cannot be modified after
118112
instantiation.
@@ -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,12 +168,12 @@ 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

182175
def __repr__(self):
183-
return "%s(type_codecs=%r, fallback_encoder=%r)" % (
176+
return "{}(type_codecs={!r}, fallback_encoder={!r})".format(
184177
self.__class__.__name__,
185178
self.__type_codecs,
186179
self._fallback_encoder,
@@ -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={!s}".format(
453445
document_class_repr,
454446
self.tz_aware,
455447
uuid_rep_repr,
@@ -474,7 +466,7 @@ def _options_dict(self) -> Dict[str, Any]:
474466
}
475467

476468
def __repr__(self):
477-
return "%s(%s)" % (self.__class__.__name__, self._arguments_repr())
469+
return f"{self.__class__.__name__}({self._arguments_repr()})"
478470

479471
def with_options(self, **kwargs: Any) -> "CodecOptions":
480472
"""Make a copy of this CodecOptions, overriding some options::

bson/dbref.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from bson.son import SON
2222

2323

24-
class DBRef(object):
24+
class DBRef:
2525
"""A reference to a document stored in MongoDB."""
2626

2727
__slots__ = "__collection", "__id", "__database", "__kwargs"
@@ -36,7 +36,7 @@ def __init__(
3636
id: Any,
3737
database: Optional[str] = None,
3838
_extra: Optional[Mapping[str, Any]] = None,
39-
**kwargs: Any
39+
**kwargs: Any,
4040
) -> None:
4141
"""Initialize a new :class:`DBRef`.
4242
@@ -102,10 +102,10 @@ def as_doc(self) -> SON[str, Any]:
102102
return doc
103103

104104
def __repr__(self):
105-
extra = "".join([", %s=%r" % (k, v) for k, v in self.__kwargs.items()])
105+
extra = "".join([f", {k}={v!r}" for k, v in self.__kwargs.items()])
106106
if self.database is None:
107-
return "DBRef(%r, %r%s)" % (self.collection, self.id, extra)
108-
return "DBRef(%r, %r, %r%s)" % (self.collection, self.id, self.database, extra)
107+
return f"DBRef({self.collection!r}, {self.id!r}{extra})"
108+
return f"DBRef({self.collection!r}, {self.id!r}, {self.database!r}{extra})"
109109

110110
def __eq__(self, other: Any) -> bool:
111111
if isinstance(other, DBRef):

bson/decimal128.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def _decimal_to_128(value: _VALUE_OPTIONS) -> Tuple[int, int]:
115115
return high, low
116116

117117

118-
class Decimal128(object):
118+
class Decimal128:
119119
"""BSON Decimal128 type::
120120
121121
>>> Decimal128(Decimal("0.0005"))
@@ -226,7 +226,7 @@ def __init__(self, value: _VALUE_OPTIONS) -> None:
226226
)
227227
self.__high, self.__low = value # type: ignore
228228
else:
229-
raise TypeError("Cannot convert %r to Decimal128" % (value,))
229+
raise TypeError(f"Cannot convert {value!r} to Decimal128")
230230

231231
def to_decimal(self) -> decimal.Decimal:
232232
"""Returns an instance of :class:`decimal.Decimal` for this
@@ -297,7 +297,7 @@ def __str__(self) -> str:
297297
return str(dec)
298298

299299
def __repr__(self):
300-
return "Decimal128('%s')" % (str(self),)
300+
return f"Decimal128('{str(self)}')"
301301

302302
def __setstate__(self, value: Tuple[int, int]) -> None:
303303
self.__high, self.__low = value

0 commit comments

Comments
 (0)