Skip to content

PYTHON-2504 Apply one time pyupgrade --py37-plus v3.3.2 and ruff #1196

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

Merged
merged 3 commits into from
May 11, 2023
Merged
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
17 changes: 8 additions & 9 deletions bson/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,8 @@ def get_data_and_view(data: Any) -> Tuple[Any, memoryview]:
def _raise_unknown_type(element_type: int, element_name: str) -> NoReturn:
"""Unknown type helper."""
raise InvalidBSON(
"Detected unknown BSON type %r for fieldname '%s'. Are "
"you using the latest driver version?" % (chr(element_type).encode(), element_name)
"Detected unknown BSON type {!r} for fieldname '{}'. Are "
"you using the latest driver version?".format(chr(element_type).encode(), element_name)
)


Expand Down Expand Up @@ -626,8 +626,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 @@ -942,18 +941,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: CodecOptions) -> 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 @@ -971,7 +970,7 @@ def _dict_to_bson(doc: Any, check_keys: bool, opts: CodecOptions, top_level: boo
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
4 changes: 2 additions & 2 deletions bson/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

"""Setstate and getstate functions for objects with __slots__, allowing
compatibility with default pickling protocol
compatibility with default pickling protocol
"""
from typing import Any, Mapping

Expand All @@ -33,7 +33,7 @@ def _mangle_name(name: str, prefix: str) -> str:

def _getstate_slots(self: Any) -> Mapping[Any, Any]:
prefix = self.__class__.__name__
ret = dict()
ret = {}
for name in self.__slots__:
mangled_name = _mangle_name(name, prefix)
if hasattr(self, mangled_name):
Expand Down
11 changes: 5 additions & 6 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 All @@ -330,8 +330,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
return UUID(bytes=self)

raise ValueError(
"cannot decode subtype %s to %s"
% (self.subtype, UUID_REPRESENTATION_NAMES[uuid_representation])
f"cannot decode subtype {self.subtype} to {UUID_REPRESENTATION_NAMES[uuid_representation]}"
)

@property
Expand All @@ -341,7 +340,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 +354,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})"
7 changes: 3 additions & 4 deletions bson/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tools for representing JavaScript code in BSON.
"""
"""Tools for representing JavaScript code in BSON."""

from collections.abc import Mapping as _Mapping
from typing import Any, Mapping, Optional, Type, Union
Expand Down Expand Up @@ -54,7 +53,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 +87,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
24 changes: 8 additions & 16 deletions bson/codec_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,10 @@ class TypeEncoder(abc.ABC):
@abc.abstractproperty
def python_type(self) -> Any:
"""The Python type to be converted into something serializable."""
pass

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


class TypeDecoder(abc.ABC):
Expand All @@ -84,12 +82,10 @@ class TypeDecoder(abc.ABC):
@abc.abstractproperty
def bson_type(self) -> Any:
"""The BSON type to be converted into our own type."""
pass

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


class TypeCodec(TypeEncoder, TypeDecoder):
Expand All @@ -105,14 +101,12 @@ class TypeCodec(TypeEncoder, TypeDecoder):
See :ref:`custom-type-type-codec` documentation for an example.
"""

pass


_Codec = Union[TypeEncoder, TypeDecoder, TypeCodec]
_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 @@ -164,8 +158,7 @@ def __init__(
self._decoder_map[codec.bson_type] = codec.transform_bson
if not is_valid_codec:
raise TypeError(
"Expected an instance of %s, %s, or %s, got %r instead"
% (TypeEncoder.__name__, TypeDecoder.__name__, TypeCodec.__name__, codec)
f"Expected an instance of {TypeEncoder.__name__}, {TypeDecoder.__name__}, or {TypeCodec.__name__}, got {codec!r} instead"
)

def _validate_type_encoder(self, codec: _Codec) -> None:
Expand All @@ -175,12 +168,12 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
if issubclass(cast(TypeCodec, codec).python_type, pytype):
err_msg = (
"TypeEncoders cannot change how built-in types are "
"encoded (encoder %s transforms type %s)" % (codec, pytype)
"encoded (encoder {} transforms type {})".format(codec, pytype)
)
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 @@ -446,10 +439,9 @@ def _arguments_repr(self) -> str:
)

return (
"document_class=%s, tz_aware=%r, uuid_representation=%s, "
"unicode_decode_error_handler=%r, tzinfo=%r, "
"type_registry=%r, datetime_conversion=%s"
% (
"document_class={}, tz_aware={!r}, uuid_representation={}, "
"unicode_decode_error_handler={!r}, tzinfo={!r}, "
"type_registry={!r}, datetime_conversion={!s}".format(
document_class_repr,
self.tz_aware,
uuid_rep_repr,
Expand All @@ -474,7 +466,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
Loading