Skip to content

Commit 5e92980

Browse files
committed
PYTHON-2504 Apply pyupgrade --py37-plus v3.3.2
1 parent bc9029a commit 5e92980

File tree

133 files changed

+790
-823
lines changed

Some content is hidden

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

133 files changed

+790
-823
lines changed

bson/__init__.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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/binary.py

Lines changed: 4 additions & 4 deletions
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(
@@ -341,7 +341,7 @@ def subtype(self) -> int:
341341

342342
def __getnewargs__(self) -> Tuple[bytes, int]: # type: ignore[override]
343343
# Work around http://bugs.python.org/issue7382
344-
data = super(Binary, self).__getnewargs__()[0]
344+
data = super().__getnewargs__()[0]
345345
if not isinstance(data, bytes):
346346
data = data.encode("latin-1")
347347
return data, self.__subtype
@@ -355,10 +355,10 @@ def __eq__(self, other: Any) -> bool:
355355
return False
356356

357357
def __hash__(self) -> int:
358-
return super(Binary, self).__hash__() ^ hash(self.__subtype)
358+
return super().__hash__() ^ hash(self.__subtype)
359359

360360
def __ne__(self, other: Any) -> bool:
361361
return not self == other
362362

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

bson/code.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __new__(
5454
cls: Type["Code"],
5555
code: Union[str, "Code"],
5656
scope: Optional[Mapping[str, Any]] = None,
57-
**kwargs: Any
57+
**kwargs: Any,
5858
) -> "Code":
5959
if not isinstance(code, str):
6060
raise TypeError("code must be an instance of str")
@@ -88,7 +88,7 @@ def scope(self) -> Optional[Mapping[str, Any]]:
8888
return self.__scope
8989

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

9393
def __eq__(self, other: Any) -> bool:
9494
if isinstance(other, Code):

bson/codec_options.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ class TypeCodec(TypeEncoder, TypeDecoder):
112112
_Fallback = Callable[[Any], Any]
113113

114114

115-
class TypeRegistry(object):
115+
class TypeRegistry:
116116
"""Encapsulates type codecs used in encoding and / or decoding BSON, as
117117
well as the fallback encoder. Type registries cannot be modified after
118118
instantiation.
@@ -180,7 +180,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
180180
raise TypeError(err_msg)
181181

182182
def __repr__(self):
183-
return "%s(type_codecs=%r, fallback_encoder=%r)" % (
183+
return "{}(type_codecs={!r}, fallback_encoder={!r})".format(
184184
self.__class__.__name__,
185185
self.__type_codecs,
186186
self._fallback_encoder,
@@ -474,7 +474,7 @@ def _options_dict(self) -> Dict[str, Any]:
474474
}
475475

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

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

bson/dbref.py

Lines changed: 5 additions & 5 deletions
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

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

bson/json_util.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ def __new__(
288288
strict_uuid: Optional[bool] = None,
289289
json_mode: int = JSONMode.RELAXED,
290290
*args: Any,
291-
**kwargs: Any
291+
**kwargs: Any,
292292
) -> "JSONOptions":
293293
kwargs["tz_aware"] = kwargs.get("tz_aware", False)
294294
if kwargs["tz_aware"]:
@@ -303,7 +303,7 @@ def __new__(
303303
"JSONOptions.datetime_representation must be one of LEGACY, "
304304
"NUMBERLONG, or ISO8601 from DatetimeRepresentation."
305305
)
306-
self = cast(JSONOptions, super(JSONOptions, cls).__new__(cls, *args, **kwargs))
306+
self = cast(JSONOptions, super().__new__(cls, *args, **kwargs))
307307
if json_mode not in (JSONMode.LEGACY, JSONMode.RELAXED, JSONMode.CANONICAL):
308308
raise ValueError(
309309
"JSONOptions.json_mode must be one of LEGACY, RELAXED, "
@@ -358,13 +358,13 @@ def _arguments_repr(self) -> str:
358358
self.datetime_representation,
359359
self.strict_uuid,
360360
self.json_mode,
361-
super(JSONOptions, self)._arguments_repr(),
361+
super()._arguments_repr(),
362362
)
363363
)
364364

365365
def _options_dict(self) -> Dict[Any, Any]:
366366
# TODO: PYTHON-2442 use _asdict() instead
367-
options_dict = super(JSONOptions, self)._options_dict()
367+
options_dict = super()._options_dict()
368368
options_dict.update(
369369
{
370370
"strict_number_long": self.strict_number_long,
@@ -492,7 +492,7 @@ def _json_convert(obj: Any, json_options: JSONOptions = DEFAULT_JSON_OPTIONS) ->
492492
if hasattr(obj, "items"):
493493
return SON(((k, _json_convert(v, json_options)) for k, v in obj.items()))
494494
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
495-
return list((_json_convert(v, json_options) for v in obj))
495+
return list(_json_convert(v, json_options) for v in obj)
496496
try:
497497
return default(obj, json_options)
498498
except TypeError:
@@ -568,9 +568,9 @@ def _parse_legacy_regex(doc: Any) -> Any:
568568
def _parse_legacy_uuid(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUID]:
569569
"""Decode a JSON legacy $uuid to Python UUID."""
570570
if len(doc) != 1:
571-
raise TypeError("Bad $uuid, extra field(s): %s" % (doc,))
571+
raise TypeError(f"Bad $uuid, extra field(s): {doc}")
572572
if not isinstance(doc["$uuid"], str):
573-
raise TypeError("$uuid must be a string: %s" % (doc,))
573+
raise TypeError(f"$uuid must be a string: {doc}")
574574
if json_options.uuid_representation == UuidRepresentation.UNSPECIFIED:
575575
return Binary.from_uuid(uuid.UUID(doc["$uuid"]))
576576
else:
@@ -613,11 +613,11 @@ def _parse_canonical_binary(doc: Any, json_options: JSONOptions) -> Union[Binary
613613
b64 = binary["base64"]
614614
subtype = binary["subType"]
615615
if not isinstance(b64, str):
616-
raise TypeError("$binary base64 must be a string: %s" % (doc,))
616+
raise TypeError(f"$binary base64 must be a string: {doc}")
617617
if not isinstance(subtype, str) or len(subtype) > 2:
618-
raise TypeError("$binary subType must be a string at most 2 characters: %s" % (doc,))
618+
raise TypeError(f"$binary subType must be a string at most 2 characters: {doc}")
619619
if len(binary) != 2:
620-
raise TypeError('$binary must include only "base64" and "subType" components: %s' % (doc,))
620+
raise TypeError(f'$binary must include only "base64" and "subType" components: {doc}')
621621

622622
data = base64.b64decode(b64.encode())
623623
return _binary_or_uuid(data, int(subtype, 16), json_options)
@@ -629,7 +629,7 @@ def _parse_canonical_datetime(
629629
"""Decode a JSON datetime to python datetime.datetime."""
630630
dtm = doc["$date"]
631631
if len(doc) != 1:
632-
raise TypeError("Bad $date, extra field(s): %s" % (doc,))
632+
raise TypeError(f"Bad $date, extra field(s): {doc}")
633633
# mongoexport 2.6 and newer
634634
if isinstance(dtm, str):
635635
# Parse offset
@@ -692,31 +692,31 @@ def _parse_canonical_datetime(
692692
def _parse_canonical_oid(doc: Any) -> ObjectId:
693693
"""Decode a JSON ObjectId to bson.objectid.ObjectId."""
694694
if len(doc) != 1:
695-
raise TypeError("Bad $oid, extra field(s): %s" % (doc,))
695+
raise TypeError(f"Bad $oid, extra field(s): {doc}")
696696
return ObjectId(doc["$oid"])
697697

698698

699699
def _parse_canonical_symbol(doc: Any) -> str:
700700
"""Decode a JSON symbol to Python string."""
701701
symbol = doc["$symbol"]
702702
if len(doc) != 1:
703-
raise TypeError("Bad $symbol, extra field(s): %s" % (doc,))
703+
raise TypeError(f"Bad $symbol, extra field(s): {doc}")
704704
return str(symbol)
705705

706706

707707
def _parse_canonical_code(doc: Any) -> Code:
708708
"""Decode a JSON code to bson.code.Code."""
709709
for key in doc:
710710
if key not in ("$code", "$scope"):
711-
raise TypeError("Bad $code, extra field(s): %s" % (doc,))
711+
raise TypeError(f"Bad $code, extra field(s): {doc}")
712712
return Code(doc["$code"], scope=doc.get("$scope"))
713713

714714

715715
def _parse_canonical_regex(doc: Any) -> Regex:
716716
"""Decode a JSON regex to bson.regex.Regex."""
717717
regex = doc["$regularExpression"]
718718
if len(doc) != 1:
719-
raise TypeError("Bad $regularExpression, extra field(s): %s" % (doc,))
719+
raise TypeError(f"Bad $regularExpression, extra field(s): {doc}")
720720
if len(regex) != 2:
721721
raise TypeError(
722722
'Bad $regularExpression must include only "pattern"'
@@ -739,65 +739,65 @@ def _parse_canonical_dbpointer(doc: Any) -> Any:
739739
"""Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef."""
740740
dbref = doc["$dbPointer"]
741741
if len(doc) != 1:
742-
raise TypeError("Bad $dbPointer, extra field(s): %s" % (doc,))
742+
raise TypeError(f"Bad $dbPointer, extra field(s): {doc}")
743743
if isinstance(dbref, DBRef):
744744
dbref_doc = dbref.as_doc()
745745
# DBPointer must not contain $db in its value.
746746
if dbref.database is not None:
747-
raise TypeError("Bad $dbPointer, extra field $db: %s" % (dbref_doc,))
747+
raise TypeError(f"Bad $dbPointer, extra field $db: {dbref_doc}")
748748
if not isinstance(dbref.id, ObjectId):
749-
raise TypeError("Bad $dbPointer, $id must be an ObjectId: %s" % (dbref_doc,))
749+
raise TypeError(f"Bad $dbPointer, $id must be an ObjectId: {dbref_doc}")
750750
if len(dbref_doc) != 2:
751-
raise TypeError("Bad $dbPointer, extra field(s) in DBRef: %s" % (dbref_doc,))
751+
raise TypeError(f"Bad $dbPointer, extra field(s) in DBRef: {dbref_doc}")
752752
return dbref
753753
else:
754-
raise TypeError("Bad $dbPointer, expected a DBRef: %s" % (doc,))
754+
raise TypeError(f"Bad $dbPointer, expected a DBRef: {doc}")
755755

756756

757757
def _parse_canonical_int32(doc: Any) -> int:
758758
"""Decode a JSON int32 to python int."""
759759
i_str = doc["$numberInt"]
760760
if len(doc) != 1:
761-
raise TypeError("Bad $numberInt, extra field(s): %s" % (doc,))
761+
raise TypeError(f"Bad $numberInt, extra field(s): {doc}")
762762
if not isinstance(i_str, str):
763-
raise TypeError("$numberInt must be string: %s" % (doc,))
763+
raise TypeError(f"$numberInt must be string: {doc}")
764764
return int(i_str)
765765

766766

767767
def _parse_canonical_int64(doc: Any) -> Int64:
768768
"""Decode a JSON int64 to bson.int64.Int64."""
769769
l_str = doc["$numberLong"]
770770
if len(doc) != 1:
771-
raise TypeError("Bad $numberLong, extra field(s): %s" % (doc,))
771+
raise TypeError(f"Bad $numberLong, extra field(s): {doc}")
772772
return Int64(l_str)
773773

774774

775775
def _parse_canonical_double(doc: Any) -> float:
776776
"""Decode a JSON double to python float."""
777777
d_str = doc["$numberDouble"]
778778
if len(doc) != 1:
779-
raise TypeError("Bad $numberDouble, extra field(s): %s" % (doc,))
779+
raise TypeError(f"Bad $numberDouble, extra field(s): {doc}")
780780
if not isinstance(d_str, str):
781-
raise TypeError("$numberDouble must be string: %s" % (doc,))
781+
raise TypeError(f"$numberDouble must be string: {doc}")
782782
return float(d_str)
783783

784784

785785
def _parse_canonical_decimal128(doc: Any) -> Decimal128:
786786
"""Decode a JSON decimal128 to bson.decimal128.Decimal128."""
787787
d_str = doc["$numberDecimal"]
788788
if len(doc) != 1:
789-
raise TypeError("Bad $numberDecimal, extra field(s): %s" % (doc,))
789+
raise TypeError(f"Bad $numberDecimal, extra field(s): {doc}")
790790
if not isinstance(d_str, str):
791-
raise TypeError("$numberDecimal must be string: %s" % (doc,))
791+
raise TypeError(f"$numberDecimal must be string: {doc}")
792792
return Decimal128(d_str)
793793

794794

795795
def _parse_canonical_minkey(doc: Any) -> MinKey:
796796
"""Decode a JSON MinKey to bson.min_key.MinKey."""
797797
if type(doc["$minKey"]) is not int or doc["$minKey"] != 1:
798-
raise TypeError("$minKey value must be 1: %s" % (doc,))
798+
raise TypeError(f"$minKey value must be 1: {doc}")
799799
if len(doc) != 1:
800-
raise TypeError("Bad $minKey, extra field(s): %s" % (doc,))
800+
raise TypeError(f"Bad $minKey, extra field(s): {doc}")
801801
return MinKey()
802802

803803

@@ -806,7 +806,7 @@ def _parse_canonical_maxkey(doc: Any) -> MaxKey:
806806
if type(doc["$maxKey"]) is not int or doc["$maxKey"] != 1:
807807
raise TypeError("$maxKey value must be 1: %s", (doc,))
808808
if len(doc) != 1:
809-
raise TypeError("Bad $minKey, extra field(s): %s" % (doc,))
809+
raise TypeError(f"Bad $minKey, extra field(s): {doc}")
810810
return MaxKey()
811811

812812

@@ -839,7 +839,7 @@ def default(obj: Any, json_options: JSONOptions = DEFAULT_JSON_OPTIONS) -> Any:
839839
millis = int(obj.microsecond / 1000)
840840
fracsecs = ".%03d" % (millis,) if millis else ""
841841
return {
842-
"$date": "%s%s%s" % (obj.strftime("%Y-%m-%dT%H:%M:%S"), fracsecs, tz_string)
842+
"$date": "{}{}{}".format(obj.strftime("%Y-%m-%dT%H:%M:%S"), fracsecs, tz_string)
843843
}
844844

845845
millis = _datetime_to_millis(obj)

bson/max_key.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from typing import Any
1818

1919

20-
class MaxKey(object):
20+
class MaxKey:
2121
"""MongoDB internal MaxKey type."""
2222

2323
__slots__ = ()

0 commit comments

Comments
 (0)