Skip to content

Commit 527cbdd

Browse files
authored
PYTHON-5537 Update typing dependencies (#2524)
1 parent 8879f2b commit 527cbdd

File tree

16 files changed

+100
-75
lines changed

16 files changed

+100
-75
lines changed

bson/binary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ class Binary(bytes):
298298

299299
def __new__(
300300
cls: Type[Binary],
301-
data: Union[memoryview, bytes, _mmap, _array[Any]],
301+
data: Union[memoryview, bytes, bytearray, _mmap, _array[Any]],
302302
subtype: int = BINARY_SUBTYPE,
303303
) -> Binary:
304304
if not isinstance(subtype, int):

bson/raw_bson.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@
6060

6161

6262
def _inflate_bson(
63-
bson_bytes: bytes, codec_options: CodecOptions[RawBSONDocument], raw_array: bool = False
63+
bson_bytes: bytes | memoryview,
64+
codec_options: CodecOptions[RawBSONDocument],
65+
raw_array: bool = False,
6466
) -> dict[str, Any]:
6567
"""Inflates the top level fields of a BSON document.
6668
@@ -85,7 +87,9 @@ class RawBSONDocument(Mapping[str, Any]):
8587
__codec_options: CodecOptions[RawBSONDocument]
8688

8789
def __init__(
88-
self, bson_bytes: bytes, codec_options: Optional[CodecOptions[RawBSONDocument]] = None
90+
self,
91+
bson_bytes: bytes | memoryview,
92+
codec_options: Optional[CodecOptions[RawBSONDocument]] = None,
8993
) -> None:
9094
"""Create a new :class:`RawBSONDocument`
9195
@@ -135,7 +139,7 @@ class from the standard library so it can be used like a read-only
135139
_get_object_size(bson_bytes, 0, len(bson_bytes))
136140

137141
@property
138-
def raw(self) -> bytes:
142+
def raw(self) -> bytes | memoryview:
139143
"""The raw BSON bytes composing this document."""
140144
return self.__raw
141145

@@ -153,7 +157,7 @@ def __inflated(self) -> Mapping[str, Any]:
153157

154158
@staticmethod
155159
def _inflate_bson(
156-
bson_bytes: bytes, codec_options: CodecOptions[RawBSONDocument]
160+
bson_bytes: bytes | memoryview, codec_options: CodecOptions[RawBSONDocument]
157161
) -> Mapping[str, Any]:
158162
return _inflate_bson(bson_bytes, codec_options)
159163

@@ -180,7 +184,7 @@ class _RawArrayBSONDocument(RawBSONDocument):
180184

181185
@staticmethod
182186
def _inflate_bson(
183-
bson_bytes: bytes, codec_options: CodecOptions[RawBSONDocument]
187+
bson_bytes: bytes | memoryview, codec_options: CodecOptions[RawBSONDocument]
184188
) -> Mapping[str, Any]:
185189
return _inflate_bson(bson_bytes, codec_options, raw_array=True)
186190

bson/son.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def popitem(self) -> Tuple[_Key, _Value]:
143143
del self[k]
144144
return (k, v)
145145

146-
def update(self, other: Optional[Any] = None, **kwargs: _Value) -> None: # type: ignore[override]
146+
def update(self, other: Optional[Any] = None, **kwargs: _Value) -> None:
147147
# Make progressively weaker assumptions about "other"
148148
if other is None:
149149
pass

bson/typings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,4 @@
2828
_DocumentOut = Union[MutableMapping[str, Any], "RawBSONDocument"]
2929
_DocumentType = TypeVar("_DocumentType", bound=Mapping[str, Any])
3030
_DocumentTypeArg = TypeVar("_DocumentTypeArg", bound=Mapping[str, Any])
31-
_ReadableBuffer = Union[bytes, memoryview, "mmap", "array"] # type: ignore[type-arg]
31+
_ReadableBuffer = Union[bytes, memoryview, bytearray, "mmap", "array"] # type: ignore[type-arg]

pymongo/asynchronous/cursor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1009,7 +1009,7 @@ def _deepcopy(
10091009
else:
10101010
if not isinstance(key, RE_TYPE):
10111011
key = copy.deepcopy(key, memo) # noqa: PLW2901
1012-
y[key] = value
1012+
y[key] = value # type:ignore[index]
10131013
return y
10141014

10151015
def _prepare_to_die(self, already_killed: bool) -> tuple[int, Optional[_CursorAddress]]:

pymongo/asynchronous/encryption.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def spawn(self) -> None:
264264
args.extend(self.opts._mongocryptd_spawn_args)
265265
_spawn_daemon(args)
266266

267-
async def mark_command(self, database: str, cmd: bytes) -> bytes:
267+
async def mark_command(self, database: str, cmd: bytes) -> bytes | memoryview:
268268
"""Mark a command for encryption.
269269
270270
:param database: The database on which to run this command.
@@ -291,7 +291,7 @@ async def mark_command(self, database: str, cmd: bytes) -> bytes:
291291
)
292292
return res.raw
293293

294-
async def fetch_keys(self, filter: bytes) -> AsyncGenerator[bytes, None]:
294+
async def fetch_keys(self, filter: bytes) -> AsyncGenerator[bytes | memoryview, None]:
295295
"""Yields one or more keys from the key vault.
296296
297297
:param filter: The filter to pass to find.
@@ -463,7 +463,7 @@ async def encrypt(
463463
# TODO: PYTHON-1922 avoid decoding the encrypted_cmd.
464464
return _inflate_bson(encrypted_cmd, DEFAULT_RAW_BSON_OPTIONS)
465465

466-
async def decrypt(self, response: bytes) -> Optional[bytes]:
466+
async def decrypt(self, response: bytes | memoryview) -> Optional[bytes]:
467467
"""Decrypt a MongoDB command response.
468468
469469
:param response: A MongoDB command response as BSON.

pymongo/asynchronous/helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ async def _getaddrinfo(
7878
socket.SocketKind,
7979
int,
8080
str,
81-
tuple[str, int] | tuple[str, int, int, int],
81+
tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes],
8282
]
8383
]:
8484
if not _IS_SYNC:

pymongo/compression_support.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def compress(data: bytes) -> bytes:
152152
return zstandard.ZstdCompressor().compress(data)
153153

154154

155-
def decompress(data: bytes, compressor_id: int) -> bytes:
155+
def decompress(data: bytes | memoryview, compressor_id: int) -> bytes:
156156
if compressor_id == SnappyContext.compressor_id:
157157
# python-snappy doesn't support the buffer interface.
158158
# https://github.com/andrix/python-snappy/issues/65

pymongo/message.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,15 +1352,17 @@ class _OpReply:
13521352
UNPACK_FROM = struct.Struct("<iqii").unpack_from
13531353
OP_CODE = 1
13541354

1355-
def __init__(self, flags: int, cursor_id: int, number_returned: int, documents: bytes):
1355+
def __init__(
1356+
self, flags: int, cursor_id: int, number_returned: int, documents: bytes | memoryview
1357+
):
13561358
self.flags = flags
13571359
self.cursor_id = Int64(cursor_id)
13581360
self.number_returned = number_returned
13591361
self.documents = documents
13601362

13611363
def raw_response(
13621364
self, cursor_id: Optional[int] = None, user_fields: Optional[Mapping[str, Any]] = None
1363-
) -> list[bytes]:
1365+
) -> list[bytes | memoryview]:
13641366
"""Check the response header from the database, without decoding BSON.
13651367
13661368
Check the response for errors and unpack.
@@ -1448,7 +1450,7 @@ def more_to_come(self) -> bool:
14481450
return False
14491451

14501452
@classmethod
1451-
def unpack(cls, msg: bytes) -> _OpReply:
1453+
def unpack(cls, msg: bytes | memoryview) -> _OpReply:
14521454
"""Construct an _OpReply from raw bytes."""
14531455
# PYTHON-945: ignore starting_from field.
14541456
flags, cursor_id, _, number_returned = cls.UNPACK_FROM(msg)
@@ -1470,7 +1472,7 @@ class _OpMsg:
14701472
MORE_TO_COME = 1 << 1
14711473
EXHAUST_ALLOWED = 1 << 16 # Only present on requests.
14721474

1473-
def __init__(self, flags: int, payload_document: bytes):
1475+
def __init__(self, flags: int, payload_document: bytes | memoryview):
14741476
self.flags = flags
14751477
self.payload_document = payload_document
14761478

@@ -1512,7 +1514,7 @@ def command_response(self, codec_options: CodecOptions[Any]) -> dict[str, Any]:
15121514
"""Unpack a command response."""
15131515
return self.unpack_response(codec_options=codec_options)[0]
15141516

1515-
def raw_command_response(self) -> bytes:
1517+
def raw_command_response(self) -> bytes | memoryview:
15161518
"""Return the bytes of the command response."""
15171519
return self.payload_document
15181520

@@ -1522,7 +1524,7 @@ def more_to_come(self) -> bool:
15221524
return bool(self.flags & self.MORE_TO_COME)
15231525

15241526
@classmethod
1525-
def unpack(cls, msg: bytes) -> _OpMsg:
1527+
def unpack(cls, msg: bytes | memoryview) -> _OpMsg:
15261528
"""Construct an _OpMsg from raw bytes."""
15271529
flags, first_payload_type, first_payload_size = cls.UNPACK_FROM(msg)
15281530
if flags != 0:
@@ -1541,7 +1543,7 @@ def unpack(cls, msg: bytes) -> _OpMsg:
15411543
return cls(flags, payload_document)
15421544

15431545

1544-
_UNPACK_REPLY: dict[int, Callable[[bytes], Union[_OpReply, _OpMsg]]] = {
1546+
_UNPACK_REPLY: dict[int, Callable[[bytes | memoryview], Union[_OpReply, _OpMsg]]] = {
15451547
_OpReply.OP_CODE: _OpReply.unpack,
15461548
_OpMsg.OP_CODE: _OpMsg.unpack,
15471549
}

pymongo/network_layer.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def sock(self) -> Union[socket.socket, _sslConn]:
246246
def fileno(self) -> int:
247247
return self.conn.fileno()
248248

249-
def recv_into(self, buffer: bytes) -> int:
249+
def recv_into(self, buffer: bytes | memoryview) -> int:
250250
return self.conn.recv_into(buffer)
251251

252252

@@ -533,14 +533,14 @@ def _resolve_pending(self, exc: Optional[Exception] = None) -> None:
533533
fut = self._pending_listeners.popleft()
534534
fut.set_result(b"")
535535

536-
def _read(self, bytes_needed: int) -> memoryview:
536+
def _read(self, bytes_needed: int) -> bytes:
537537
"""Read bytes."""
538538
# Send the bytes to the listener.
539539
if self._bytes_ready < bytes_needed:
540540
bytes_needed = self._bytes_ready
541541
self._bytes_ready -= bytes_needed
542542

543-
output_buf = bytearray(bytes_needed)
543+
output_buf = memoryview(bytearray(bytes_needed))
544544
n_remaining = bytes_needed
545545
out_index = 0
546546
while n_remaining > 0:
@@ -557,7 +557,7 @@ def _read(self, bytes_needed: int) -> memoryview:
557557
output_buf[out_index : out_index + buf_size] = buffer[:]
558558
out_index += buf_size
559559
n_remaining -= buf_size
560-
return memoryview(output_buf)
560+
return bytes(output_buf)
561561

562562

563563
async def async_sendall(conn: PyMongoBaseProtocol, buf: bytes) -> None:
@@ -670,6 +670,7 @@ def receive_message(
670670
f"Message length ({length!r}) is larger than server max "
671671
f"message size ({max_message_size!r})"
672672
)
673+
data: bytes | memoryview
673674
if op_code == 2012:
674675
op_code, _, compressor_id = _UNPACK_COMPRESSION_HEADER(receive_data(conn, 9, deadline))
675676
data = decompress(receive_data(conn, length - 25, deadline), compressor_id)

0 commit comments

Comments
 (0)