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
5 changes: 4 additions & 1 deletion .evergreen/scripts/generate_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import sys
from itertools import product
from typing import TYPE_CHECKING

from generate_config_utils import (
ALL_PYTHONS,
Expand Down Expand Up @@ -36,7 +37,6 @@
write_variants_to_file,
zip_cycle,
)
from shrub.v3.evg_build_variant import BuildVariant
from shrub.v3.evg_command import (
FunctionCall,
archive_targz_pack,
Expand All @@ -49,6 +49,9 @@
from shrub.v3.evg_task import EvgTask, EvgTaskDependency, EvgTaskRef
from utils import PERF_PYTHON_VERSION

if TYPE_CHECKING:
from shrub.v3.evg_build_variant import BuildVariant

##############
# Variants
##############
Expand Down
5 changes: 3 additions & 2 deletions bson/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ def _raw_to_dict(
result: _T,
raw_array: bool = False,
) -> _T:
return cast(_T, _cbson._raw_to_dict(data, position, obj_end, opts, result, raw_array))
return cast("_T", _cbson._raw_to_dict(data, position, obj_end, opts, result, raw_array))

else:

Expand All @@ -618,7 +618,8 @@ def _raw_to_dict(
) -> _T:
data, view = get_data_and_view(data)
return cast(
_T, _elements_to_dict(data, view, position, obj_end, opts, result, raw_array=raw_array)
"_T",
_elements_to_dict(data, view, position, obj_end, opts, result, raw_array=raw_array),
)


Expand Down
2 changes: 1 addition & 1 deletion bson/codec_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
from bson import _BUILT_IN_TYPES

for pytype in _BUILT_IN_TYPES:
if issubclass(cast(TypeCodec, codec).python_type, pytype):
if issubclass(cast("TypeCodec", codec).python_type, pytype):
err_msg = (
"TypeEncoders cannot change how built-in types are "
f"encoded (encoder {codec} transforms type {pytype})"
Expand Down
2 changes: 1 addition & 1 deletion bson/datetime_ms.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def as_datetime(
and ``tz_info``. Defaults to
:const:`~bson.codec_options.DEFAULT_CODEC_OPTIONS`.
"""
return cast(datetime.datetime, _millis_to_datetime(self._value, codec_options))
return cast("datetime.datetime", _millis_to_datetime(self._value, codec_options))

def __int__(self) -> int:
return self._value
Expand Down
4 changes: 2 additions & 2 deletions bson/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ def __new__(
"JSONOptions.datetime_representation must be one of LEGACY, "
"NUMBERLONG, or ISO8601 from DatetimeRepresentation."
)
self = cast(Self, super().__new__(cls, *args, **kwargs))
self = cast("Self", 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, or CANONICAL from JSONMode."
Expand Down Expand Up @@ -557,7 +557,7 @@ def _binary_or_uuid(data: Any, subtype: int, json_options: JSONOptions) -> Binar
return binary_value.as_uuid(uuid_representation)

if subtype == 0:
return cast(uuid.UUID, data)
return cast("uuid.UUID", data)
return Binary(data, subtype)


Expand Down
2 changes: 1 addition & 1 deletion gridfs/asynchronous/grid_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ async def upload_from_stream(
) as gin:
await gin.write(source)

return cast(ObjectId, gin._id)
return cast("ObjectId", gin._id)

@_csot.apply
async def upload_from_stream_with_id(
Expand Down
2 changes: 1 addition & 1 deletion gridfs/synchronous/grid_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ def upload_from_stream(
with self.open_upload_stream(filename, chunk_size_bytes, metadata, session=session) as gin:
gin.write(source)

return cast(ObjectId, gin._id)
return cast("ObjectId", gin._id)

@_csot.apply
def upload_from_stream_with_id(
Expand Down
2 changes: 1 addition & 1 deletion pymongo/_csot.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def csot_wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
return func(self, *args, **kwargs)
return func(self, *args, **kwargs)

return cast(F, csot_wrapper)
return cast("F", csot_wrapper)


def apply_write_concern(cmd: MutableMapping[str, Any], write_concern: WriteConcern | None) -> None:
Expand Down
2 changes: 1 addition & 1 deletion pymongo/asynchronous/_kms_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ async def _connect_kms(
)
# Any: the sync version's callback returns a plain socket.
result: Any = kms_connect_callback(
KMSConnectContext(host=address[0], port=cast(int, address[1]), timeout=timeout)
KMSConnectContext(host=address[0], port=cast("int", address[1]), timeout=timeout)
)
remaining = _csot.remaining()
if remaining is None or _IS_SYNC:
Expand Down
23 changes: 12 additions & 11 deletions pymongo/asynchronous/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,6 @@

import warnings
from collections import abc
from collections.abc import (
Callable,
Coroutine,
Iterable,
Iterator,
Mapping,
MutableMapping,
Sequence,
)
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -123,6 +114,16 @@ class ReturnDocument:


if TYPE_CHECKING:
from collections.abc import (
Callable,
Coroutine,
Iterable,
Iterator,
Mapping,
MutableMapping,
Sequence,
)

import bson
from bson.timestamp import Timestamp
from pymongo.asynchronous.aggregation import _AggregationCommand
Expand Down Expand Up @@ -2537,7 +2538,7 @@ async def _list_indexes(
) -> AsyncCommandCursor[MutableMapping[str, Any]]:
codec_options: CodecOptions[Mapping[str, Any]] = CodecOptions(SON)
coll = cast(
AsyncCollection[MutableMapping[str, Any]],
"AsyncCollection[MutableMapping[str, Any]]",
self.with_options(codec_options=codec_options, read_preference=ReadPreference.PRIMARY),
)
read_pref = (session and session._txn_read_preference()) or ReadPreference.PRIMARY
Expand Down Expand Up @@ -3071,7 +3072,7 @@ async def aggregate_raw_batches(
kwargs["comment"] = comment
async with self._database.client._tmp_session(session) as s:
return cast(
AsyncRawBatchCursor[_DocumentType],
"AsyncRawBatchCursor[_DocumentType]",
await self._aggregate(
_CollectionRawAggregationCommand,
pipeline,
Expand Down
2 changes: 1 addition & 1 deletion pymongo/asynchronous/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ def _unpack_response(
# OP_MSG returns firstBatch/nextBatch documents as a BSON array
# Re-assemble the array of documents into a document stream
_convert_raw_document_lists_to_streams(raw_response[0])
return cast(list["_DocumentOut"], raw_response)
return cast("list[_DocumentOut]", raw_response)

async def explain(self) -> _DocumentType:
"""Returns an explain plan record for this cursor.
Expand Down
11 changes: 6 additions & 5 deletions pymongo/asynchronous/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

from __future__ import annotations

from collections.abc import Mapping, MutableMapping, Sequence
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Expand All @@ -42,6 +41,8 @@
from pymongo.typings import _CollationIn, _DocumentType, _DocumentTypeArg, _Pipeline

if TYPE_CHECKING:
from collections.abc import Mapping, MutableMapping, Sequence

import bson
import bson.codec_options
from bson.timestamp import Timestamp
Expand Down Expand Up @@ -303,7 +304,7 @@ async def _get_encrypted_fields(
) -> Mapping[str, Any] | None:
encrypted_fields = kwargs.get("encryptedFields")
if encrypted_fields:
return cast(Mapping[str, Any], deepcopy(encrypted_fields))
return cast("Mapping[str, Any]", deepcopy(encrypted_fields))
if (
self.client.options.auto_encryption_opts
and self.client.options.auto_encryption_opts._encrypted_fields_map
Expand All @@ -312,7 +313,7 @@ async def _get_encrypted_fields(
)
):
return cast(
Mapping[str, Any],
"Mapping[str, Any]",
deepcopy(
self.client.options.auto_encryption_opts._encrypted_fields_map[
f"{self.name}.{coll_name}"
Expand All @@ -322,7 +323,7 @@ async def _get_encrypted_fields(
if ask_db and self.client.options.auto_encryption_opts:
options = await self[coll_name].options()
if options.get("encryptedFields"):
return cast(Mapping[str, Any], deepcopy(options["encryptedFields"]))
return cast("Mapping[str, Any]", deepcopy(options["encryptedFields"]))
return None

# See PYTHON-3084.
Expand Down Expand Up @@ -1085,7 +1086,7 @@ async def _list_collections(
) -> AsyncCommandCursor[MutableMapping[str, Any]]:
"""Internal listCollections helper."""
coll = cast(
AsyncCollection[MutableMapping[str, Any]],
"AsyncCollection[MutableMapping[str, Any]]",
self.get_collection("$cmd", read_preference=read_preference),
)
cmd = {"listCollections": 1, "cursor": {}}
Expand Down
12 changes: 6 additions & 6 deletions pymongo/asynchronous/encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson
from pymongo import _csot, _op_id
from pymongo.asynchronous._kms_connect import _KMS_CONNECT_TIMEOUT, _connect_kms
from pymongo.asynchronous.collection import AsyncCollection
from pymongo.asynchronous.database import AsyncDatabase
from pymongo.asynchronous.mongo_client import AsyncMongoClient
from pymongo.daemon import _spawn_daemon
Expand Down Expand Up @@ -95,6 +94,7 @@
from pymongocrypt.mongocrypt import MongoCryptKmsContext

from pymongo._kms_connect_shared import AsyncKMSConnectCallback
from pymongo.asynchronous.collection import AsyncCollection
from pymongo.asynchronous.cursor import AsyncCursor
from pymongo.results import DeleteResult

Expand Down Expand Up @@ -128,7 +128,7 @@ def __init__(
else:
self.client_ref = None
self.key_vault_coll: AsyncCollection[RawBSONDocument] | None = cast(
AsyncCollection[RawBSONDocument],
"AsyncCollection[RawBSONDocument]",
key_vault_coll.with_options(
codec_options=_KEY_VAULT_OPTS,
read_concern=ReadConcern(level="majority"),
Expand Down Expand Up @@ -452,7 +452,7 @@ async def decrypt(self, response: bytes | memoryview) -> bytes | None:
with _wrap_encryption_errors():
# Don't let decryption's sub-commands inherit the in-flight op's id.
with _op_id._OpIdContext(None):
return cast(bytes, await self._auto_encrypter.decrypt(response))
return cast("bytes", await self._auto_encrypter.decrypt(response))

def _check_closed(self) -> None:
if self._closed:
Expand Down Expand Up @@ -795,7 +795,7 @@ async def create_data_key(
self._check_closed()
with _wrap_encryption_errors():
return cast(
Binary,
"Binary",
await self._encryption.create_data_key(
kms_provider,
master_key=master_key,
Expand Down Expand Up @@ -909,7 +909,7 @@ async def encrypt(
Added the `query_type` and `contention_factor` parameters.
"""
return cast(
Binary,
"Binary",
await self._encrypt_helper(
value=value,
algorithm=algorithm,
Expand Down Expand Up @@ -965,7 +965,7 @@ async def encrypt_expression(
.. versionadded:: 4.4
"""
return cast(
RawBSONDocument,
"RawBSONDocument",
await self._encrypt_helper(
value=expression,
algorithm=algorithm,
Expand Down
2 changes: 1 addition & 1 deletion pymongo/asynchronous/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ async def inner(*args: Any, **kwargs: Any) -> Any:
return await func(*args, **kwargs)
raise

return cast(F, inner)
return cast("F", inner)


async def _getaddrinfo(
Expand Down
4 changes: 2 additions & 2 deletions pymongo/asynchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1608,7 +1608,7 @@ def get_default_database(
if self._default_database_name is None and default is None:
raise ConfigurationError("No default database name defined or provided.")

name = cast(str, self._default_database_name or default)
name = cast("str", self._default_database_name or default)
return database.AsyncDatabase(
self, name, codec_options, read_preference, write_concern, read_concern
)
Expand Down Expand Up @@ -2409,7 +2409,7 @@ async def server_info(
Added ``session`` parameter.
"""
return cast( # type: ignore[redundant-cast]
dict[str, Any],
"dict[str, Any]",
await self.admin.command(
"buildinfo", read_preference=ReadPreference.PRIMARY, session=session
),
Expand Down
2 changes: 1 addition & 1 deletion pymongo/asynchronous/topology.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ async def select_servers(
)

return [
cast(Server, self.get_server_by_address(sd.address)) for sd in server_descriptions
cast("Server", self.get_server_by_address(sd.address)) for sd in server_descriptions
]

async def _select_servers_loop(
Expand Down
4 changes: 2 additions & 2 deletions pymongo/auth_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def _xor(fir: bytes, sec: bytes) -> bytes:
def _parse_scram_response(response: bytes) -> dict[bytes, bytes]:
"""Split a scram response into key, value pairs."""
return dict(
typing.cast(typing.Tuple[bytes, bytes], item.split(b"=", 1))
typing.cast("typing.Tuple[bytes, bytes]", item.split(b"=", 1))
for item in response.split(b",")
)

Expand Down Expand Up @@ -290,7 +290,7 @@ def from_credentials(
) -> _AuthContext | None:
spec_cls = spec_auth_map.get(creds.mechanism)
if spec_cls:
return cast(_AuthContext, spec_cls(creds, address))
return cast("_AuthContext", spec_cls(creds, address))
return None

def speculate_command(self) -> MutableMapping[str, Any] | None:
Expand Down
5 changes: 3 additions & 2 deletions pymongo/client_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

from __future__ import annotations

from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Any, cast

from bson.codec_options import _parse_codec_options
Expand All @@ -39,6 +38,8 @@
from pymongo.write_concern import WriteConcern, validate_boolean

if TYPE_CHECKING:
from collections.abc import Mapping, Sequence

from bson.codec_options import CodecOptions
from pymongo.auth_shared import MongoCredential
from pymongo.encryption_options import AutoEncryptionOpts
Expand Down Expand Up @@ -164,7 +165,7 @@ def _parse_pool_options(
connect_timeout = options.get("connecttimeoutms", common.CONNECT_TIMEOUT)
socket_timeout = options.get("sockettimeoutms")
wait_queue_timeout = options.get("waitqueuetimeoutms", common.WAIT_QUEUE_TIMEOUT)
event_listeners = cast(Sequence[_EventListener] | None, options.get("event_listeners"))
event_listeners = cast("Sequence[_EventListener] | None", options.get("event_listeners"))
appname = options.get("appname")
driver = options.get("driver")
server_api = options.get("server_api")
Expand Down
2 changes: 1 addition & 1 deletion pymongo/client_session_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,5 +774,5 @@ def __del__(self) -> None:
# Reuse the cursor closing machinery to return the socket to the
# pool soon. _close_cursor_soon expects the IO-specific
# _ConnectionManager, which conn_mgr is at runtime.
self.client._close_cursor_soon(0, None, cast(Any, self.conn_mgr))
self.client._close_cursor_soon(0, None, cast("Any", self.conn_mgr))
self.conn_mgr = None
2 changes: 1 addition & 1 deletion pymongo/cursor_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,7 +1010,7 @@ def where(self, code: str | Code) -> Self:
if self._has_filter:
spec = dict(self._spec)
else:
spec = cast(dict, self._spec) # type: ignore[type-arg]
spec = cast("dict", self._spec) # type: ignore[type-arg]
spec["$where"] = code
self._spec = spec
return self
Expand Down
2 changes: 1 addition & 1 deletion pymongo/mongo_client_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def _retryable_error_doc(exc: PyMongoError) -> Mapping[str, Any] | None:
wces = exc.details["writeConcernErrors"]
return wces[-1] if wces else None
if isinstance(exc, (NotPrimaryError, OperationFailure)):
return cast(Mapping[str, Any], exc.details)
return cast("Mapping[str, Any]", exc.details)
return None


Expand Down
Loading
Loading