From f9d7860eeb891ce6b644b86ae7f5bb4a9a9f0488 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Thu, 12 Nov 2026 10:23:46 -0500 Subject: [PATCH 1/2] PYTHON-6260 Opt into all ruff TC rules --- .evergreen/scripts/generate_config.py | 5 ++++- bson/__init__.py | 5 +++-- bson/codec_options.py | 2 +- bson/datetime_ms.py | 2 +- bson/json_util.py | 4 ++-- gridfs/asynchronous/grid_file.py | 2 +- gridfs/synchronous/grid_file.py | 2 +- pymongo/_csot.py | 2 +- pymongo/asynchronous/_kms_connect.py | 2 +- pymongo/asynchronous/collection.py | 23 ++++++++++---------- pymongo/asynchronous/cursor.py | 2 +- pymongo/asynchronous/database.py | 11 +++++----- pymongo/asynchronous/encryption.py | 12 +++++------ pymongo/asynchronous/helpers.py | 2 +- pymongo/asynchronous/mongo_client.py | 4 ++-- pymongo/asynchronous/topology.py | 2 +- pymongo/auth_shared.py | 4 ++-- pymongo/client_options.py | 5 +++-- pymongo/client_session_shared.py | 2 +- pymongo/cursor_shared.py | 2 +- pymongo/mongo_client_shared.py | 2 +- pymongo/results.py | 26 ++++++++++++----------- pymongo/server_selectors.py | 2 +- pymongo/socket_checker.py | 4 ++-- pymongo/synchronous/_kms_connect.py | 2 +- pymongo/synchronous/collection.py | 21 +++++++++--------- pymongo/synchronous/cursor.py | 2 +- pymongo/synchronous/database.py | 11 +++++----- pymongo/synchronous/encryption.py | 12 +++++------ pymongo/synchronous/helpers.py | 2 +- pymongo/synchronous/mongo_client.py | 4 ++-- pymongo/synchronous/topology.py | 2 +- pymongo/topology_description.py | 2 +- pymongo/uri_parser_shared.py | 4 ++-- pyproject.toml | 3 +-- test/asynchronous/test_client_metadata.py | 2 +- test/test_client_metadata.py | 2 +- test/test_ocsp_support.py | 4 ++-- test/test_typing.py | 2 +- tools/test_synchro.py | 4 +++- 40 files changed, 110 insertions(+), 98 deletions(-) diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 3b45e52971..270f9be75a 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -3,6 +3,7 @@ import sys from itertools import product +from typing import TYPE_CHECKING from generate_config_utils import ( ALL_PYTHONS, @@ -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, @@ -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 ############## diff --git a/bson/__init__.py b/bson/__init__.py index 7c23a85ce8..801ae77e74 100644 --- a/bson/__init__.py +++ b/bson/__init__.py @@ -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: @@ -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), ) diff --git a/bson/codec_options.py b/bson/codec_options.py index 8ee7d0c246..1727e2e094 100644 --- a/bson/codec_options.py +++ b/bson/codec_options.py @@ -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})" diff --git a/bson/datetime_ms.py b/bson/datetime_ms.py index d82ad9d1cb..d659323717 100644 --- a/bson/datetime_ms.py +++ b/bson/datetime_ms.py @@ -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 diff --git a/bson/json_util.py b/bson/json_util.py index 2cef3d9f03..98f4612683 100644 --- a/bson/json_util.py +++ b/bson/json_util.py @@ -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." @@ -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) diff --git a/gridfs/asynchronous/grid_file.py b/gridfs/asynchronous/grid_file.py index c6d84a9c2e..b245125c52 100644 --- a/gridfs/asynchronous/grid_file.py +++ b/gridfs/asynchronous/grid_file.py @@ -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( diff --git a/gridfs/synchronous/grid_file.py b/gridfs/synchronous/grid_file.py index da2bc57fc3..7372c484c0 100644 --- a/gridfs/synchronous/grid_file.py +++ b/gridfs/synchronous/grid_file.py @@ -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( diff --git a/pymongo/_csot.py b/pymongo/_csot.py index ea541b40ed..25654240ed 100644 --- a/pymongo/_csot.py +++ b/pymongo/_csot.py @@ -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: diff --git a/pymongo/asynchronous/_kms_connect.py b/pymongo/asynchronous/_kms_connect.py index 768d279a0c..b8be206cc2 100644 --- a/pymongo/asynchronous/_kms_connect.py +++ b/pymongo/asynchronous/_kms_connect.py @@ -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: diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index e21ecb1855..3a8b7f83b8 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -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, @@ -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 @@ -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 @@ -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, diff --git a/pymongo/asynchronous/cursor.py b/pymongo/asynchronous/cursor.py index 7829db9d1f..52b5572c08 100644 --- a/pymongo/asynchronous/cursor.py +++ b/pymongo/asynchronous/cursor.py @@ -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. diff --git a/pymongo/asynchronous/database.py b/pymongo/asynchronous/database.py index 589a467816..b958409b3e 100644 --- a/pymongo/asynchronous/database.py +++ b/pymongo/asynchronous/database.py @@ -16,7 +16,6 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping, Sequence from copy import deepcopy from typing import ( TYPE_CHECKING, @@ -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 @@ -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 @@ -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}" @@ -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. @@ -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": {}} diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index 2f996dfe2c..113b7b6612 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -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 @@ -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 @@ -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"), @@ -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: @@ -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, @@ -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, @@ -965,7 +965,7 @@ async def encrypt_expression( .. versionadded:: 4.4 """ return cast( - RawBSONDocument, + "RawBSONDocument", await self._encrypt_helper( value=expression, algorithm=algorithm, diff --git a/pymongo/asynchronous/helpers.py b/pymongo/asynchronous/helpers.py index 26b4ade00a..8a3cc6e882 100644 --- a/pymongo/asynchronous/helpers.py +++ b/pymongo/asynchronous/helpers.py @@ -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( diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index c6dbf175b9..2fdba127b3 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -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 ) @@ -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 ), diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index c356a5321c..1471830ddf 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -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( diff --git a/pymongo/auth_shared.py b/pymongo/auth_shared.py index d9798c576a..582d75e815 100644 --- a/pymongo/auth_shared.py +++ b/pymongo/auth_shared.py @@ -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",") ) @@ -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: diff --git a/pymongo/client_options.py b/pymongo/client_options.py index 7ef34c578a..f9dc402574 100644 --- a/pymongo/client_options.py +++ b/pymongo/client_options.py @@ -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 @@ -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 @@ -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") diff --git a/pymongo/client_session_shared.py b/pymongo/client_session_shared.py index b07963a05e..6e4ac0378f 100644 --- a/pymongo/client_session_shared.py +++ b/pymongo/client_session_shared.py @@ -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 diff --git a/pymongo/cursor_shared.py b/pymongo/cursor_shared.py index 73f4d51a72..6fdf784750 100644 --- a/pymongo/cursor_shared.py +++ b/pymongo/cursor_shared.py @@ -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 diff --git a/pymongo/mongo_client_shared.py b/pymongo/mongo_client_shared.py index a46eb57928..6ad69e1e67 100644 --- a/pymongo/mongo_client_shared.py +++ b/pymongo/mongo_client_shared.py @@ -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 diff --git a/pymongo/results.py b/pymongo/results.py index 6b4bfd6c1b..f34de54309 100644 --- a/pymongo/results.py +++ b/pymongo/results.py @@ -19,11 +19,13 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast from pymongo.errors import InvalidOperation +if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + class _WriteResult: """Base class for write result classes.""" @@ -158,7 +160,7 @@ def modified_count(self) -> int: """The number of documents modified.""" self._raise_if_unacknowledged("modified_count") assert self.__raw_result is not None - return cast(int, self.__raw_result.get("nModified")) + return cast("int", self.__raw_result.get("nModified")) @property def upserted_id(self) -> Any: @@ -229,34 +231,34 @@ def bulk_api_result(self) -> dict[str, Any]: def inserted_count(self) -> int: """The number of documents inserted.""" self._raise_if_unacknowledged("inserted_count") - return cast(int, self.__bulk_api_result.get("nInserted")) + return cast("int", self.__bulk_api_result.get("nInserted")) @property def matched_count(self) -> int: """The number of documents matched for an update.""" self._raise_if_unacknowledged("matched_count") - return cast(int, self.__bulk_api_result.get("nMatched")) + return cast("int", self.__bulk_api_result.get("nMatched")) @property def modified_count(self) -> int: """The number of documents modified.""" self._raise_if_unacknowledged("modified_count") - return cast(int, self.__bulk_api_result.get("nModified")) + return cast("int", self.__bulk_api_result.get("nModified")) @property def deleted_count(self) -> int: """The number of documents deleted.""" self._raise_if_unacknowledged("deleted_count") if "nRemoved" in self.__bulk_api_result: - return cast(int, self.__bulk_api_result.get("nRemoved")) + return cast("int", self.__bulk_api_result.get("nRemoved")) else: - return cast(int, self.__bulk_api_result.get("nDeleted")) + return cast("int", self.__bulk_api_result.get("nDeleted")) @property def upserted_count(self) -> int: """The number of documents upserted.""" self._raise_if_unacknowledged("upserted_count") - return cast(int, self.__bulk_api_result.get("nUpserted")) + return cast("int", self.__bulk_api_result.get("nUpserted")) class BulkWriteResult(_BulkWriteResultBase): @@ -339,7 +341,7 @@ def insert_results(self) -> Mapping[int, InsertOneResult]: self._raise_if_unacknowledged("insert_results") self._raise_if_not_verbose("insert_results") return cast( - Mapping[int, InsertOneResult], + "Mapping[int, InsertOneResult]", self.bulk_api_result.get("insertResults"), ) @@ -349,7 +351,7 @@ def update_results(self) -> Mapping[int, UpdateResult]: self._raise_if_unacknowledged("update_results") self._raise_if_not_verbose("update_results") return cast( - Mapping[int, UpdateResult], + "Mapping[int, UpdateResult]", self.bulk_api_result.get("updateResults"), ) @@ -359,6 +361,6 @@ def delete_results(self) -> Mapping[int, DeleteResult]: self._raise_if_unacknowledged("delete_results") self._raise_if_not_verbose("delete_results") return cast( - Mapping[int, DeleteResult], + "Mapping[int, DeleteResult]", self.bulk_api_result.get("deleteResults"), ) diff --git a/pymongo/server_selectors.py b/pymongo/server_selectors.py index b4aded09cb..7639cfc1f3 100644 --- a/pymongo/server_selectors.py +++ b/pymongo/server_selectors.py @@ -71,7 +71,7 @@ def secondary_with_max_last_write_date(self) -> ServerDescription | None: secondaries = secondary_server_selector(self) if secondaries.server_descriptions: return max( - secondaries.server_descriptions, key=lambda sd: cast(float, sd.last_write_date) + secondaries.server_descriptions, key=lambda sd: cast("float", sd.last_write_date) ) return None diff --git a/pymongo/socket_checker.py b/pymongo/socket_checker.py index 9af7bbe0b7..1f81acabe7 100644 --- a/pymongo/socket_checker.py +++ b/pymongo/socket_checker.py @@ -26,9 +26,9 @@ def _errno_from_exception(exc: BaseException) -> int | None: if hasattr(exc, "errno"): - return cast(int, exc.errno) + return cast("int", exc.errno) if exc.args: - return cast(int, exc.args[0]) + return cast("int", exc.args[0]) return None diff --git a/pymongo/synchronous/_kms_connect.py b/pymongo/synchronous/_kms_connect.py index 3ebef0cc2c..c9cf5acf4c 100644 --- a/pymongo/synchronous/_kms_connect.py +++ b/pymongo/synchronous/_kms_connect.py @@ -85,7 +85,7 @@ 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: diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index bf0c3c77e4..34b00cec50 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -18,14 +18,6 @@ import warnings from collections import abc -from collections.abc import ( - Callable, - Iterable, - Iterator, - Mapping, - MutableMapping, - Sequence, -) from typing import ( TYPE_CHECKING, Any, @@ -122,6 +114,15 @@ class ReturnDocument: if TYPE_CHECKING: + from collections.abc import ( + Callable, + Iterable, + Iterator, + Mapping, + MutableMapping, + Sequence, + ) + import bson from bson.timestamp import Timestamp from pymongo.collation import Collation @@ -2528,7 +2529,7 @@ def _list_indexes( ) -> CommandCursor[MutableMapping[str, Any]]: codec_options: CodecOptions[Mapping[str, Any]] = CodecOptions(SON) coll = cast( - Collection[MutableMapping[str, Any]], + "Collection[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 @@ -3056,7 +3057,7 @@ def aggregate_raw_batches( kwargs["comment"] = comment with self._database.client._tmp_session(session) as s: return cast( - RawBatchCursor[_DocumentType], + "RawBatchCursor[_DocumentType]", self._aggregate( _CollectionRawAggregationCommand, pipeline, diff --git a/pymongo/synchronous/cursor.py b/pymongo/synchronous/cursor.py index 5dbf71f523..32e03ee9cf 100644 --- a/pymongo/synchronous/cursor.py +++ b/pymongo/synchronous/cursor.py @@ -439,7 +439,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) def explain(self) -> _DocumentType: """Returns an explain plan record for this cursor. diff --git a/pymongo/synchronous/database.py b/pymongo/synchronous/database.py index 49aff61619..a683cc177d 100644 --- a/pymongo/synchronous/database.py +++ b/pymongo/synchronous/database.py @@ -16,7 +16,6 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping, Sequence from copy import deepcopy from typing import ( TYPE_CHECKING, @@ -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 @@ -303,7 +304,7 @@ 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 @@ -312,7 +313,7 @@ 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}" @@ -322,7 +323,7 @@ def _get_encrypted_fields( if ask_db and self.client.options.auto_encryption_opts: options = 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. @@ -1085,7 +1086,7 @@ def _list_collections( ) -> CommandCursor[MutableMapping[str, Any]]: """Internal listCollections helper.""" coll = cast( - Collection[MutableMapping[str, Any]], + "Collection[MutableMapping[str, Any]]", self.get_collection("$cmd", read_preference=read_preference), ) cmd = {"listCollections": 1, "cursor": {}} diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 95ff05eaef..774e3347c2 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -80,7 +80,6 @@ from pymongo.read_concern import ReadConcern from pymongo.ssl_support import BLOCKING_IO_ERRORS, get_ssl_context from pymongo.synchronous._kms_connect import _KMS_CONNECT_TIMEOUT, _connect_kms -from pymongo.synchronous.collection import Collection from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient from pymongo.typings import _DocumentType, _DocumentTypeArg @@ -95,6 +94,7 @@ from pymongo._kms_connect_shared import KMSConnectCallback from pymongo.results import DeleteResult + from pymongo.synchronous.collection import Collection from pymongo.synchronous.cursor import Cursor @@ -127,7 +127,7 @@ def __init__( else: self.client_ref = None self.key_vault_coll: Collection[RawBSONDocument] | None = cast( - Collection[RawBSONDocument], + "Collection[RawBSONDocument]", key_vault_coll.with_options( codec_options=_KEY_VAULT_OPTS, read_concern=ReadConcern(level="majority"), @@ -449,7 +449,7 @@ 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, self._auto_encrypter.decrypt(response)) + return cast("bytes", self._auto_encrypter.decrypt(response)) def _check_closed(self) -> None: if self._closed: @@ -788,7 +788,7 @@ def create_data_key( self._check_closed() with _wrap_encryption_errors(): return cast( - Binary, + "Binary", self._encryption.create_data_key( kms_provider, master_key=master_key, @@ -902,7 +902,7 @@ def encrypt( Added the `query_type` and `contention_factor` parameters. """ return cast( - Binary, + "Binary", self._encrypt_helper( value=value, algorithm=algorithm, @@ -958,7 +958,7 @@ def encrypt_expression( .. versionadded:: 4.4 """ return cast( - RawBSONDocument, + "RawBSONDocument", self._encrypt_helper( value=expression, algorithm=algorithm, diff --git a/pymongo/synchronous/helpers.py b/pymongo/synchronous/helpers.py index 695259c952..4038df19fa 100644 --- a/pymongo/synchronous/helpers.py +++ b/pymongo/synchronous/helpers.py @@ -72,7 +72,7 @@ def inner(*args: Any, **kwargs: Any) -> Any: return func(*args, **kwargs) raise - return cast(F, inner) + return cast("F", inner) def _getaddrinfo( diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index 825ca41e81..04977efe05 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -1606,7 +1606,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.Database( self, name, codec_options, read_preference, write_concern, read_concern ) @@ -2399,7 +2399,7 @@ def server_info(self, session: client_session.ClientSession | None = None) -> di Added ``session`` parameter. """ return cast( # type: ignore[redundant-cast] - dict[str, Any], + "dict[str, Any]", self.admin.command( "buildinfo", read_preference=ReadPreference.PRIMARY, session=session ), diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index df7600b33e..b7a9bd366c 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -203,7 +203,7 @@ 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 ] def _select_servers_loop( diff --git a/pymongo/topology_description.py b/pymongo/topology_description.py index 47f00addf3..8be5ae8a56 100644 --- a/pymongo/topology_description.py +++ b/pymongo/topology_description.py @@ -276,7 +276,7 @@ def _apply_local_threshold(self, selection: Selection | None) -> list[ServerDesc return [ s for s in selection.server_descriptions - if (cast(float, s.round_trip_time) - fastest) <= threshold + if (cast("float", s.round_trip_time) - fastest) <= threshold ] def _filter_servers(self, deprioritized_servers: list[ServerDescription] | None = None) -> None: diff --git a/pymongo/uri_parser_shared.py b/pymongo/uri_parser_shared.py index db29bb1d3f..da567cb12d 100644 --- a/pymongo/uri_parser_shared.py +++ b/pymongo/uri_parser_shared.py @@ -423,7 +423,7 @@ def split_options( options = _normalize_options(options) if validate: - options = cast(_CaseInsensitiveDictionary, validate_options(options, warn)) + options = cast("_CaseInsensitiveDictionary", validate_options(options, warn)) if options.get("authsource") == "": raise InvalidURI("the authSource database cannot be an empty string") @@ -507,7 +507,7 @@ def _parse_kms_tls_options( opts = _CaseInsensitiveDictionary(options) opts = _handle_security_options(opts) opts = _normalize_options(opts) - opts = cast(_CaseInsensitiveDictionary, validate_options(opts)) + opts = cast("_CaseInsensitiveDictionary", validate_options(opts)) ssl_context, allow_invalid_hostnames = _parse_ssl_options(opts, is_sync) if ssl_context is None: raise ConfigurationError("TLS is required for KMS providers") diff --git a/pyproject.toml b/pyproject.toml index 0bc52f4a9e..1390828fc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -218,8 +218,7 @@ extend-select = [ "YTT", # flake8-2020 "EXE", # flake8-executable "ASYNC", # flake8-async - "TC001", # flake8-type-checking: typing-only first-party imports - "TC003", # flake8-type-checking: typing-only stdlib imports + "TC", # flake8-type-checking ] ignore = [ "PLR", # Design related pylint codes diff --git a/test/asynchronous/test_client_metadata.py b/test/asynchronous/test_client_metadata.py index afc1aac1a3..3d8d0660cf 100644 --- a/test/asynchronous/test_client_metadata.py +++ b/test/asynchronous/test_client_metadata.py @@ -297,7 +297,7 @@ async def test_10_entries_in_driver_name_and_driver_version_correspond_by_index( self.assertIsNotNone(name0) self.assertIsNotNone(version0) - version0 = cast(str, version0) + version0 = cast("str", version0) driver_name = name0.split("|")[0] driver_version = version0.split("|")[0] diff --git a/test/test_client_metadata.py b/test/test_client_metadata.py index e1c53513cd..1af37ae46b 100644 --- a/test/test_client_metadata.py +++ b/test/test_client_metadata.py @@ -297,7 +297,7 @@ def test_10_entries_in_driver_name_and_driver_version_correspond_by_index(self): self.assertIsNotNone(name0) self.assertIsNotNone(version0) - version0 = cast(str, version0) + version0 = cast("str", version0) driver_name = name0.split("|")[0] driver_version = version0.split("|")[0] diff --git a/test/test_ocsp_support.py b/test/test_ocsp_support.py index 294688a4a3..021507411e 100644 --- a/test/test_ocsp_support.py +++ b/test/test_ocsp_support.py @@ -281,7 +281,7 @@ def test_by_name_match(self): cert2.subject = "other" cert2.issuer = "issuer" - result = _get_certs_by_name([cert1, cert2], issuer, cast(Name, "responder")) + result = _get_certs_by_name([cert1, cert2], issuer, cast("Name", "responder")) self.assertEqual(result, [cert1]) def test_by_name_no_match(self): @@ -291,7 +291,7 @@ def test_by_name_no_match(self): cert.subject = "other" cert.issuer = "issuer" - result = _get_certs_by_name([cert], issuer, cast(Name, "responder")) + result = _get_certs_by_name([cert], issuer, cast("Name", "responder")) self.assertEqual(result, []) diff --git a/test/test_typing.py b/test/test_typing.py index 546f732f8d..85b5d9bc1f 100644 --- a/test/test_typing.py +++ b/test/test_typing.py @@ -92,7 +92,7 @@ def inner(*args, **kwargs): raise unittest.SkipTest("Used for Type Checking Only") func(*args, **kwargs) - return cast(FuncT, inner) + return cast("FuncT", inner) class TestMypyFails(unittest.TestCase): diff --git a/tools/test_synchro.py b/tools/test_synchro.py index 3f46f52044..e6a1cc3b8f 100644 --- a/tools/test_synchro.py +++ b/tools/test_synchro.py @@ -4,9 +4,11 @@ import sys from pathlib import Path +from typing import TYPE_CHECKING from unittest.mock import patch -import pytest +if TYPE_CHECKING: + import pytest sys.path.insert(0, str(Path(__file__).parent)) From ecc98d299aae2c94fbe6c51ca702082424b3f71a Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Thu, 12 Nov 2026 11:01:30 -0500 Subject: [PATCH 2/2] Fix comment whitespace --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 1390828fc3..d4256282cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -218,7 +218,7 @@ extend-select = [ "YTT", # flake8-2020 "EXE", # flake8-executable "ASYNC", # flake8-async - "TC", # flake8-type-checking + "TC", # flake8-type-checking ] ignore = [ "PLR", # Design related pylint codes