Skip to content

PYTHON-2504 Apply pyupgrade --py36-plus v2.31.0 #882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions bson/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,8 +531,7 @@ def gen_list_name() -> Generator[bytes, None, None]:
The first 1000 keys are returned from a pre-built cache. All
subsequent keys are generated on the fly.
"""
for name in _LIST_NAMES:
yield name
yield from _LIST_NAMES

counter = itertools.count(1000)
while True:
Expand Down Expand Up @@ -840,18 +839,18 @@ def _name_value_to_bson(
name, fallback_encoder(value), check_keys, opts, in_fallback_call=True
)

raise InvalidDocument("cannot encode object: %r, of type: %r" % (value, type(value)))
raise InvalidDocument(f"cannot encode object: {value!r}, of type: {type(value)!r}")


def _element_to_bson(key: Any, value: Any, check_keys: bool, opts: Any) -> bytes:
"""Encode a single key, value pair."""
if not isinstance(key, str):
raise InvalidDocument("documents must have only string keys, key was %r" % (key,))
raise InvalidDocument(f"documents must have only string keys, key was {key!r}")
if check_keys:
if key.startswith("$"):
raise InvalidDocument("key %r must not start with '$'" % (key,))
raise InvalidDocument(f"key {key!r} must not start with '$'")
if "." in key:
raise InvalidDocument("key %r must not contain '.'" % (key,))
raise InvalidDocument(f"key {key!r} must not contain '.'")

name = _make_name(key)
return _name_value_to_bson(name, value, check_keys, opts)
Expand All @@ -869,7 +868,7 @@ def _dict_to_bson(doc: Any, check_keys: bool, opts: Any, top_level: bool = True)
if not top_level or key != "_id":
elements.append(_element_to_bson(key, value, check_keys, opts))
except AttributeError:
raise TypeError("encoder expected a mapping type but got: %r" % (doc,))
raise TypeError(f"encoder expected a mapping type but got: {doc!r}")

encoded = b"".join(elements)
return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"
Expand Down
8 changes: 4 additions & 4 deletions bson/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
.. versionadded:: 3.11
"""
if self.subtype not in ALL_UUID_SUBTYPES:
raise ValueError("cannot decode subtype %s as a uuid" % (self.subtype,))
raise ValueError(f"cannot decode subtype {self.subtype} as a uuid")

if uuid_representation not in ALL_UUID_REPRESENTATIONS:
raise ValueError(
Expand Down Expand Up @@ -341,7 +341,7 @@ def subtype(self) -> int:

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

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

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

def __repr__(self):
return "Binary(%s, %s)" % (bytes.__repr__(self), self.__subtype)
return f"Binary({bytes.__repr__(self)}, {self.__subtype})"
4 changes: 2 additions & 2 deletions bson/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __new__(
cls: Type["Code"],
code: Union[str, "Code"],
scope: Optional[Mapping[str, Any]] = None,
**kwargs: Any
**kwargs: Any,
) -> "Code":
if not isinstance(code, str):
raise TypeError("code must be an instance of str")
Expand Down Expand Up @@ -88,7 +88,7 @@ def scope(self) -> Optional[Mapping[str, Any]]:
return self.__scope

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

def __eq__(self, other: Any) -> bool:
if isinstance(other, Code):
Expand Down
6 changes: 3 additions & 3 deletions bson/codec_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ class TypeCodec(TypeEncoder, TypeDecoder):
_Fallback = Callable[[Any], Any]


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

def __repr__(self):
return "%s(type_codecs=%r, fallback_encoder=%r)" % (
return "{}(type_codecs={!r}, fallback_encoder={!r})".format(
self.__class__.__name__,
self.__type_codecs,
self._fallback_encoder,
Expand Down Expand Up @@ -372,7 +372,7 @@ def _options_dict(self) -> Dict[str, Any]:
}

def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self._arguments_repr())
return f"{self.__class__.__name__}({self._arguments_repr()})"

def with_options(self, **kwargs: Any) -> "CodecOptions":
"""Make a copy of this CodecOptions, overriding some options::
Expand Down
10 changes: 5 additions & 5 deletions bson/dbref.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from bson.son import SON


class DBRef(object):
class DBRef:
"""A reference to a document stored in MongoDB."""

__slots__ = "__collection", "__id", "__database", "__kwargs"
Expand All @@ -36,7 +36,7 @@ def __init__(
id: Any,
database: Optional[str] = None,
_extra: Optional[Mapping[str, Any]] = None,
**kwargs: Any
**kwargs: Any,
) -> None:
"""Initialize a new :class:`DBRef`.

Expand Down Expand Up @@ -102,10 +102,10 @@ def as_doc(self) -> SON[str, Any]:
return doc

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

def __eq__(self, other: Any) -> bool:
if isinstance(other, DBRef):
Expand Down
6 changes: 3 additions & 3 deletions bson/decimal128.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def _decimal_to_128(value: _VALUE_OPTIONS) -> Tuple[int, int]:
return high, low


class Decimal128(object):
class Decimal128:
"""BSON Decimal128 type::

>>> Decimal128(Decimal("0.0005"))
Expand Down Expand Up @@ -226,7 +226,7 @@ def __init__(self, value: _VALUE_OPTIONS) -> None:
)
self.__high, self.__low = value # type: ignore
else:
raise TypeError("Cannot convert %r to Decimal128" % (value,))
raise TypeError(f"Cannot convert {value!r} to Decimal128")

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

def __repr__(self):
return "Decimal128('%s')" % (str(self),)
return f"Decimal128('{str(self)}')"

def __setstate__(self, value: Tuple[int, int]) -> None:
self.__high, self.__low = value
Expand Down
62 changes: 31 additions & 31 deletions bson/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def __new__(
strict_uuid: Optional[bool] = None,
json_mode: int = JSONMode.RELAXED,
*args: Any,
**kwargs: Any
**kwargs: Any,
) -> "JSONOptions":
kwargs["tz_aware"] = kwargs.get("tz_aware", False)
if kwargs["tz_aware"]:
Expand All @@ -274,7 +274,7 @@ def __new__(
"JSONOptions.datetime_representation must be one of LEGACY, "
"NUMBERLONG, or ISO8601 from DatetimeRepresentation."
)
self = cast(JSONOptions, super(JSONOptions, cls).__new__(cls, *args, **kwargs))
self = cast(JSONOptions, super().__new__(cls, *args, **kwargs))
if json_mode not in (JSONMode.LEGACY, JSONMode.RELAXED, JSONMode.CANONICAL):
raise ValueError(
"JSONOptions.json_mode must be one of LEGACY, RELAXED, "
Expand Down Expand Up @@ -329,13 +329,13 @@ def _arguments_repr(self) -> str:
self.datetime_representation,
self.strict_uuid,
self.json_mode,
super(JSONOptions, self)._arguments_repr(),
super()._arguments_repr(),
)
)

def _options_dict(self) -> Dict[Any, Any]:
# TODO: PYTHON-2442 use _asdict() instead
options_dict = super(JSONOptions, self)._options_dict()
options_dict = super()._options_dict()
options_dict.update(
{
"strict_number_long": self.strict_number_long,
Expand Down Expand Up @@ -458,7 +458,7 @@ def _json_convert(obj: Any, json_options: JSONOptions = DEFAULT_JSON_OPTIONS) ->
if hasattr(obj, "items"):
return SON(((k, _json_convert(v, json_options)) for k, v in obj.items()))
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
return list((_json_convert(v, json_options) for v in obj))
return list(_json_convert(v, json_options) for v in obj)
try:
return default(obj, json_options)
except TypeError:
Expand Down Expand Up @@ -534,9 +534,9 @@ def _parse_legacy_regex(doc: Any) -> Any:
def _parse_legacy_uuid(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUID]:
"""Decode a JSON legacy $uuid to Python UUID."""
if len(doc) != 1:
raise TypeError("Bad $uuid, extra field(s): %s" % (doc,))
raise TypeError(f"Bad $uuid, extra field(s): {doc}")
if not isinstance(doc["$uuid"], str):
raise TypeError("$uuid must be a string: %s" % (doc,))
raise TypeError(f"$uuid must be a string: {doc}")
if json_options.uuid_representation == UuidRepresentation.UNSPECIFIED:
return Binary.from_uuid(uuid.UUID(doc["$uuid"]))
else:
Expand Down Expand Up @@ -579,11 +579,11 @@ def _parse_canonical_binary(doc: Any, json_options: JSONOptions) -> Union[Binary
b64 = binary["base64"]
subtype = binary["subType"]
if not isinstance(b64, str):
raise TypeError("$binary base64 must be a string: %s" % (doc,))
raise TypeError(f"$binary base64 must be a string: {doc}")
if not isinstance(subtype, str) or len(subtype) > 2:
raise TypeError("$binary subType must be a string at most 2 characters: %s" % (doc,))
raise TypeError(f"$binary subType must be a string at most 2 characters: {doc}")
if len(binary) != 2:
raise TypeError('$binary must include only "base64" and "subType" components: %s' % (doc,))
raise TypeError(f'$binary must include only "base64" and "subType" components: {doc}')

data = base64.b64decode(b64.encode())
return _binary_or_uuid(data, int(subtype, 16), json_options)
Expand All @@ -593,7 +593,7 @@ def _parse_canonical_datetime(doc: Any, json_options: JSONOptions) -> datetime.d
"""Decode a JSON datetime to python datetime.datetime."""
dtm = doc["$date"]
if len(doc) != 1:
raise TypeError("Bad $date, extra field(s): %s" % (doc,))
raise TypeError(f"Bad $date, extra field(s): {doc}")
# mongoexport 2.6 and newer
if isinstance(dtm, str):
# Parse offset
Expand Down Expand Up @@ -651,31 +651,31 @@ def _parse_canonical_datetime(doc: Any, json_options: JSONOptions) -> datetime.d
def _parse_canonical_oid(doc: Any) -> ObjectId:
"""Decode a JSON ObjectId to bson.objectid.ObjectId."""
if len(doc) != 1:
raise TypeError("Bad $oid, extra field(s): %s" % (doc,))
raise TypeError(f"Bad $oid, extra field(s): {doc}")
return ObjectId(doc["$oid"])


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


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


def _parse_canonical_regex(doc: Any) -> Regex:
"""Decode a JSON regex to bson.regex.Regex."""
regex = doc["$regularExpression"]
if len(doc) != 1:
raise TypeError("Bad $regularExpression, extra field(s): %s" % (doc,))
raise TypeError(f"Bad $regularExpression, extra field(s): {doc}")
if len(regex) != 2:
raise TypeError(
'Bad $regularExpression must include only "pattern"'
Expand All @@ -698,65 +698,65 @@ def _parse_canonical_dbpointer(doc: Any) -> Any:
"""Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef."""
dbref = doc["$dbPointer"]
if len(doc) != 1:
raise TypeError("Bad $dbPointer, extra field(s): %s" % (doc,))
raise TypeError(f"Bad $dbPointer, extra field(s): {doc}")
if isinstance(dbref, DBRef):
dbref_doc = dbref.as_doc()
# DBPointer must not contain $db in its value.
if dbref.database is not None:
raise TypeError("Bad $dbPointer, extra field $db: %s" % (dbref_doc,))
raise TypeError(f"Bad $dbPointer, extra field $db: {dbref_doc}")
if not isinstance(dbref.id, ObjectId):
raise TypeError("Bad $dbPointer, $id must be an ObjectId: %s" % (dbref_doc,))
raise TypeError(f"Bad $dbPointer, $id must be an ObjectId: {dbref_doc}")
if len(dbref_doc) != 2:
raise TypeError("Bad $dbPointer, extra field(s) in DBRef: %s" % (dbref_doc,))
raise TypeError(f"Bad $dbPointer, extra field(s) in DBRef: {dbref_doc}")
return dbref
else:
raise TypeError("Bad $dbPointer, expected a DBRef: %s" % (doc,))
raise TypeError(f"Bad $dbPointer, expected a DBRef: {doc}")


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


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


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


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


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


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


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

millis = bson._datetime_to_millis(obj)
Expand Down
2 changes: 1 addition & 1 deletion bson/max_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from typing import Any


class MaxKey(object):
class MaxKey:
"""MongoDB internal MaxKey type."""

__slots__ = ()
Expand Down
Loading