Skip to content
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
382 changes: 227 additions & 155 deletions bson/__init__.py

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions bson/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _setstate_slots(self: Any, state: Any) -> None:

def _mangle_name(name: str, prefix: str) -> str:
if name.startswith("__"):
prefix = "_"+prefix
prefix = "_" + prefix
else:
prefix = ""
return prefix + name
Expand All @@ -37,5 +37,5 @@ def _getstate_slots(self: Any) -> Mapping[Any, Any]:
for name in self.__slots__:
mangled_name = _mangle_name(name, prefix)
if hasattr(self, mangled_name):
ret[mangled_name] = getattr(self, mangled_name)
ret[mangled_name] = getattr(self, mangled_name)
return ret
58 changes: 34 additions & 24 deletions bson/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Any, Tuple, Type, Union, TYPE_CHECKING
from typing import TYPE_CHECKING, Any, Tuple, Type, Union
from uuid import UUID

"""Tools for representing BSON binary data.
Expand Down Expand Up @@ -163,13 +163,15 @@ class UuidRepresentation:
UuidRepresentation.STANDARD,
UuidRepresentation.PYTHON_LEGACY,
UuidRepresentation.JAVA_LEGACY,
UuidRepresentation.CSHARP_LEGACY)
UuidRepresentation.CSHARP_LEGACY,
)
UUID_REPRESENTATION_NAMES = {
UuidRepresentation.UNSPECIFIED: 'UuidRepresentation.UNSPECIFIED',
UuidRepresentation.STANDARD: 'UuidRepresentation.STANDARD',
UuidRepresentation.PYTHON_LEGACY: 'UuidRepresentation.PYTHON_LEGACY',
UuidRepresentation.JAVA_LEGACY: 'UuidRepresentation.JAVA_LEGACY',
UuidRepresentation.CSHARP_LEGACY: 'UuidRepresentation.CSHARP_LEGACY'}
UuidRepresentation.UNSPECIFIED: "UuidRepresentation.UNSPECIFIED",
UuidRepresentation.STANDARD: "UuidRepresentation.STANDARD",
UuidRepresentation.PYTHON_LEGACY: "UuidRepresentation.PYTHON_LEGACY",
UuidRepresentation.JAVA_LEGACY: "UuidRepresentation.JAVA_LEGACY",
UuidRepresentation.CSHARP_LEGACY: "UuidRepresentation.CSHARP_LEGACY",
}

MD5_SUBTYPE = 5
"""BSON binary subtype for an MD5 hash.
Expand Down Expand Up @@ -216,7 +218,11 @@ class Binary(bytes):
_type_marker = 5
__subtype: int

def __new__(cls: Type["Binary"], data: Union[memoryview, bytes, "_mmap", "_array"], subtype: int = BINARY_SUBTYPE) -> "Binary":
def __new__(
cls: Type["Binary"],
data: Union[memoryview, bytes, "_mmap", "_array"],
subtype: int = BINARY_SUBTYPE,
) -> "Binary":
if not isinstance(subtype, int):
raise TypeError("subtype must be an instance of int")
if subtype >= 256 or subtype < 0:
Expand All @@ -227,7 +233,9 @@ def __new__(cls: Type["Binary"], data: Union[memoryview, bytes, "_mmap", "_array
return self

@classmethod
def from_uuid(cls: Type["Binary"], uuid: UUID, uuid_representation: int = UuidRepresentation.STANDARD) -> "Binary":
def from_uuid(
cls: Type["Binary"], uuid: UUID, uuid_representation: int = UuidRepresentation.STANDARD
) -> "Binary":
"""Create a BSON Binary object from a Python UUID.

Creates a :class:`~bson.binary.Binary` object from a
Expand All @@ -251,8 +259,9 @@ def from_uuid(cls: Type["Binary"], uuid: UUID, uuid_representation: int = UuidRe
raise TypeError("uuid must be an instance of uuid.UUID")

if uuid_representation not in ALL_UUID_REPRESENTATIONS:
raise ValueError("uuid_representation must be a value "
"from bson.binary.UuidRepresentation")
raise ValueError(
"uuid_representation must be a value " "from bson.binary.UuidRepresentation"
)

if uuid_representation == UuidRepresentation.UNSPECIFIED:
raise ValueError(
Expand All @@ -261,7 +270,8 @@ def from_uuid(cls: Type["Binary"], uuid: UUID, uuid_representation: int = UuidRe
"converted to bson.Binary instances using "
"bson.Binary.from_uuid() or a different UuidRepresentation "
"can be configured. See the documentation for "
"UuidRepresentation for more information.")
"UuidRepresentation for more information."
)

subtype = OLD_UUID_SUBTYPE
if uuid_representation == UuidRepresentation.PYTHON_LEGACY:
Expand Down Expand Up @@ -296,12 +306,12 @@ 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("cannot decode subtype %s as a uuid" % (self.subtype,))

if uuid_representation not in ALL_UUID_REPRESENTATIONS:
raise ValueError("uuid_representation must be a value from "
"bson.binary.UuidRepresentation")
raise ValueError(
"uuid_representation must be a value from " "bson.binary.UuidRepresentation"
)

if uuid_representation == UuidRepresentation.UNSPECIFIED:
raise ValueError("uuid_representation cannot be UNSPECIFIED")
Expand All @@ -319,26 +329,26 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
if self.subtype == UUID_SUBTYPE:
return UUID(bytes=self)

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

@property
def subtype(self) -> int:
"""Subtype of this binary data.
"""
"""Subtype of this binary data."""
return self.__subtype

def __getnewargs__(self) -> Tuple[bytes, int]: # type: ignore[override]
# Work around http://bugs.python.org/issue7382
data = super(Binary, self).__getnewargs__()[0]
if not isinstance(data, bytes):
data = data.encode('latin-1')
data = data.encode("latin-1")
return data, self.__subtype

def __eq__(self, other : Any) -> bool:
def __eq__(self, other: Any) -> bool:
if isinstance(other, Binary):
return ((self.__subtype, bytes(self)) ==
(other.subtype, bytes(other)))
return (self.__subtype, bytes(self)) == (other.subtype, bytes(other))
# We don't return NotImplemented here because if we did then
# Binary("foo") == "foo" would return True, since Binary is a
# subclass of str...
Expand Down
10 changes: 7 additions & 3 deletions bson/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,12 @@ class Code(str):
_type_marker = 13
__scope: Union[Mapping[str, Any], None]

def __new__(cls: Type["Code"], code: Union[str, "Code"], scope: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> "Code":
def __new__(
cls: Type["Code"],
code: Union[str, "Code"],
scope: Optional[Mapping[str, Any]] = None,
**kwargs: Any
) -> "Code":
if not isinstance(code, str):
raise TypeError("code must be an instance of str")

Expand Down Expand Up @@ -79,8 +84,7 @@ def __new__(cls: Type["Code"], code: Union[str, "Code"], scope: Optional[Mapping

@property
def scope(self) -> Optional[Mapping[str, Any]]:
"""Scope dictionary for this instance or ``None``.
"""
"""Scope dictionary for this instance or ``None``."""
return self.__scope

def __repr__(self):
Expand Down
Loading