Skip to content

Commit 02a3652

Browse files
authored
PYTHON-3806 add types to message.py (#1312)
1 parent 43046e0 commit 02a3652

14 files changed

+405
-181
lines changed

pymongo/bulk.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def _merge_command(
153153
full_result["writeConcernErrors"].append(wce)
154154

155155

156-
def _raise_bulk_write_error(full_result: Mapping[str, Any]) -> NoReturn:
156+
def _raise_bulk_write_error(full_result: _DocumentOut) -> NoReturn:
157157
"""Raise a BulkWriteError from the full bulk api result."""
158158
if full_result["writeErrors"]:
159159
full_result["writeErrors"].sort(key=lambda error: error["index"])

pymongo/client_session.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,7 +986,7 @@ def _apply_to(
986986
self,
987987
command: MutableMapping[str, Any],
988988
is_retryable: bool,
989-
read_preference: ReadPreference,
989+
read_preference: _ServerMode,
990990
conn: Connection,
991991
) -> None:
992992
self._check_ended()

pymongo/command_cursor.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
from pymongo.errors import ConnectionFailure, InvalidOperation, OperationFailure
3434
from pymongo.message import _CursorAddress, _GetMore, _OpMsg, _OpReply, _RawBatchGetMore
3535
from pymongo.response import PinnedResponse
36-
from pymongo.typings import _Address, _DocumentType
36+
from pymongo.typings import _Address, _DocumentOut, _DocumentType
3737

3838
if TYPE_CHECKING:
3939
from pymongo.client_session import ClientSession
@@ -94,6 +94,7 @@ def __die(self, synchronous: bool = False) -> None:
9494
self.__killed = True
9595
if self.__id and not already_killed:
9696
cursor_id = self.__id
97+
assert self.__address is not None
9798
address = _CursorAddress(self.__address, self.__ns)
9899
else:
99100
# Skip killCursors.
@@ -219,7 +220,7 @@ def _unpack_response(
219220
codec_options: CodecOptions[Mapping[str, Any]],
220221
user_fields: Optional[Mapping[str, Any]] = None,
221222
legacy_response: bool = False,
222-
) -> List[Mapping[str, Any]]:
223+
) -> List[_DocumentOut]:
223224
return response.unpack_response(cursor_id, codec_options, user_fields, legacy_response)
224225

225226
def _refresh(self) -> int:
@@ -380,7 +381,7 @@ def __init__(
380381
comment,
381382
)
382383

383-
def _unpack_response(
384+
def _unpack_response( # type: ignore[override]
384385
self,
385386
response: Union[_OpReply, _OpMsg],
386387
cursor_id: Optional[int],
@@ -393,7 +394,7 @@ def _unpack_response(
393394
# OP_MSG returns firstBatch/nextBatch documents as a BSON array
394395
# Re-assemble the array of documents into a document stream
395396
_convert_raw_document_lists_to_streams(raw_response[0])
396-
return raw_response
397+
return raw_response # type: ignore[return-value]
397398

398399
def __getitem__(self, index: int) -> NoReturn:
399400
raise InvalidOperation("Cannot call __getitem__ on RawBatchCursor")

pymongo/cursor.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
_RawBatchQuery,
5858
)
5959
from pymongo.response import PinnedResponse
60-
from pymongo.typings import _Address, _CollationIn, _DocumentType
60+
from pymongo.typings import _Address, _CollationIn, _DocumentOut, _DocumentType
6161

6262
if TYPE_CHECKING:
6363
from _typeshed import SupportsItems
@@ -420,6 +420,7 @@ def __die(self, synchronous: bool = False) -> None:
420420
self.__killed = True
421421
if self.__id and not already_killed:
422422
cursor_id = self.__id
423+
assert self.__address is not None
423424
address = _CursorAddress(self.__address, f"{self.__dbname}.{self.__collname}")
424425
else:
425426
# Skip killCursors.
@@ -1129,7 +1130,7 @@ def _unpack_response(
11291130
codec_options: CodecOptions,
11301131
user_fields: Optional[Mapping[str, Any]] = None,
11311132
legacy_response: bool = False,
1132-
) -> List[Mapping[str, Any]]:
1133+
) -> List[_DocumentOut]:
11331134
return response.unpack_response(cursor_id, codec_options, user_fields, legacy_response)
11341135

11351136
def _read_preference(self) -> _ServerMode:
@@ -1355,13 +1356,13 @@ def _unpack_response(
13551356
codec_options: CodecOptions[Mapping[str, Any]],
13561357
user_fields: Optional[Mapping[str, Any]] = None,
13571358
legacy_response: bool = False,
1358-
) -> List[Mapping[str, Any]]:
1359+
) -> List[_DocumentOut]:
13591360
raw_response = response.raw_response(cursor_id, user_fields=user_fields)
13601361
if not legacy_response:
13611362
# OP_MSG returns firstBatch/nextBatch documents as a BSON array
13621363
# Re-assemble the array of documents into a document stream
13631364
_convert_raw_document_lists_to_streams(raw_response[0])
1364-
return raw_response
1365+
return cast(List["_DocumentOut"], raw_response)
13651366

13661367
def explain(self) -> _DocumentType:
13671368
"""Returns an explain plan record for this cursor.

pymongo/encryption.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,6 @@
8080
if TYPE_CHECKING:
8181
from pymongocrypt.mongocrypt import MongoCryptKmsContext
8282

83-
from pymongo.response import Response
84-
8583
_HTTPS_PORT = 443
8684
_KMS_CONNECT_TIMEOUT = CONNECT_TIMEOUT # CDRIVER-3262 redefined this value to CONNECT_TIMEOUT
8785
_MONGOCRYPTD_TIMEOUT_MS = 10000
@@ -409,7 +407,7 @@ def encrypt(
409407
encrypt_cmd = _inflate_bson(encrypted_cmd, DEFAULT_RAW_BSON_OPTIONS)
410408
return encrypt_cmd
411409

412-
def decrypt(self, response: Response) -> Optional[bytes]:
410+
def decrypt(self, response: bytes) -> Optional[bytes]:
413411
"""Decrypt a MongoDB command response.
414412
415413
:Parameters:

pymongo/errors.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,25 @@
1313
# limitations under the License.
1414

1515
"""Exceptions raised by PyMongo."""
16-
from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
16+
from __future__ import annotations
17+
18+
from typing import (
19+
TYPE_CHECKING,
20+
Any,
21+
Iterable,
22+
List,
23+
Mapping,
24+
Optional,
25+
Sequence,
26+
Tuple,
27+
Union,
28+
)
1729

1830
from bson.errors import InvalidDocument
1931

32+
if TYPE_CHECKING:
33+
from pymongo.typings import _DocumentOut
34+
2035
try:
2136
# CPython 3.7+
2237
from ssl import SSLCertVerificationError as _CertificateError
@@ -286,9 +301,9 @@ class BulkWriteError(OperationFailure):
286301
.. versionadded:: 2.7
287302
"""
288303

289-
details: Mapping[str, Any]
304+
details: _DocumentOut
290305

291-
def __init__(self, results: Mapping[str, Any]) -> None:
306+
def __init__(self, results: _DocumentOut) -> None:
292307
super().__init__("batch op errors occurred", 65, results)
293308

294309
def __reduce__(self) -> Tuple[Any, Any]:

pymongo/helpers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
if TYPE_CHECKING:
5454
from pymongo.cursor import _Hint
5555
from pymongo.operations import _IndexList
56+
from pymongo.typings import _DocumentOut
5657

5758
# From the SDAM spec, the "node is shutting down" codes.
5859
_SHUTDOWN_CODES: frozenset = frozenset(
@@ -156,7 +157,7 @@ def _index_document(index_list: _IndexList) -> SON[str, Any]:
156157

157158

158159
def _check_command_response(
159-
response: Mapping[str, Any],
160+
response: _DocumentOut,
160161
max_wire_version: Optional[int],
161162
allowable_errors: Optional[Container[Union[int, str]]] = None,
162163
parse_write_concern_error: bool = False,

0 commit comments

Comments
 (0)