From 6f995dbcdb7f896d109bd052af4241db7edbd42e Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Wed, 11 Nov 2026 14:27:23 -0500 Subject: [PATCH] PYTHON-6258 Enable ruff TC001 rule --- bson/codec_options.py | 2 +- gridfs/asynchronous/grid_file.py | 6 ++++-- gridfs/synchronous/grid_file.py | 6 ++++-- pymongo/_client_bulk_shared.py | 2 +- pymongo/asynchronous/_kms_connect.py | 2 +- pymongo/asynchronous/bulk.py | 2 +- pymongo/asynchronous/client_bulk.py | 4 ++-- pymongo/asynchronous/client_session.py | 4 ++-- pymongo/asynchronous/collection.py | 2 +- pymongo/asynchronous/database.py | 2 +- pymongo/asynchronous/encryption.py | 7 ++++--- pymongo/asynchronous/mongo_client.py | 4 ++-- pymongo/asynchronous/pool.py | 4 +++- pymongo/asynchronous/settings.py | 9 ++++++--- pymongo/change_stream_shared.py | 4 ++-- pymongo/encryption_options.py | 2 +- pymongo/encryption_shared.py | 6 ++++-- pymongo/hello.py | 6 ++++-- pymongo/message.py | 2 +- pymongo/monitoring.py | 4 ++-- pymongo/operations.py | 2 +- pymongo/pool_shared.py | 4 ++-- pymongo/server_description.py | 8 +++++--- pymongo/synchronous/_kms_connect.py | 2 +- pymongo/synchronous/bulk.py | 2 +- pymongo/synchronous/client_bulk.py | 4 ++-- pymongo/synchronous/client_session.py | 4 ++-- pymongo/synchronous/collection.py | 2 +- pymongo/synchronous/database.py | 2 +- pymongo/synchronous/encryption.py | 7 ++++--- pymongo/synchronous/mongo_client.py | 4 ++-- pymongo/synchronous/pool.py | 4 +++- pymongo/synchronous/settings.py | 9 ++++++--- pymongo/topology_description.py | 7 +++++-- pymongo/uri_parser_shared.py | 2 +- pyproject.toml | 1 + test/__init__.py | 6 ++++-- test/asynchronous/__init__.py | 6 ++++-- test/asynchronous/test_bulk.py | 9 +++++---- test/asynchronous/test_client_metadata.py | 6 ++++-- test/asynchronous/test_collection.py | 8 +++++--- .../test_connections_survive_primary_stepdown_spec.py | 6 +++++- test/asynchronous/test_cursor.py | 6 ++++-- test/asynchronous/test_encryption.py | 6 ++++-- test/asynchronous/test_grid_file.py | 6 +++++- test/asynchronous/test_gridfs.py | 6 +++++- test/asynchronous/test_sdam_monitoring_spec.py | 6 +++++- test/asynchronous/test_sfp.py | 6 ++++-- test/asynchronous/unified_format.py | 8 +++++--- test/asynchronous/utils.py | 7 +++++-- test/mockupdb/test_cursor_namespace.py | 6 +++++- test/test_bulk.py | 9 +++++---- test/test_client_metadata.py | 6 ++++-- test/test_collection.py | 8 +++++--- test/test_connections_survive_primary_stepdown_spec.py | 6 +++++- test/test_cursor.py | 6 ++++-- test/test_encryption.py | 6 ++++-- test/test_grid_file.py | 6 +++++- test/test_gridfs.py | 6 +++++- test/test_sdam_monitoring_spec.py | 6 +++++- test/test_sfp.py | 6 ++++-- test/test_topology.py | 2 +- test/test_typing.py | 2 +- test/unified_format.py | 8 +++++--- test/unified_format_shared.py | 8 +++++--- test/utils.py | 7 +++++-- 66 files changed, 217 insertions(+), 117 deletions(-) diff --git a/bson/codec_options.py b/bson/codec_options.py index 52df204042..6ffc22ebc2 100644 --- a/bson/codec_options.py +++ b/bson/codec_options.py @@ -35,7 +35,6 @@ UUID_REPRESENTATION_NAMES, UuidRepresentation, ) -from bson.typings import _DocumentType _RAW_BSON_DOCUMENT_MARKER = 101 @@ -242,6 +241,7 @@ class _BaseCodecOptions(NamedTuple): if TYPE_CHECKING: + from bson.typings import _DocumentType class CodecOptions(tuple[_DocumentType], Generic[_DocumentType]): document_class: type[_DocumentType] diff --git a/gridfs/asynchronous/grid_file.py b/gridfs/asynchronous/grid_file.py index a8a90ce1aa..1f1e860aea 100644 --- a/gridfs/asynchronous/grid_file.py +++ b/gridfs/asynchronous/grid_file.py @@ -23,7 +23,7 @@ from collections import abc from collections.abc import Iterable, Mapping from types import TracebackType -from typing import Any, NoReturn, Self, cast +from typing import TYPE_CHECKING, Any, NoReturn, Self, cast from bson.int64 import Int64 from bson.objectid import ObjectId @@ -45,7 +45,6 @@ _clear_entity_type_registry, ) from pymongo import ASCENDING, DESCENDING, WriteConcern, _csot -from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.cursor import AsyncCursor from pymongo.asynchronous.database import AsyncDatabase @@ -62,6 +61,9 @@ from pymongo.helpers_shared import _check_write_command_response from pymongo.read_preferences import ReadPreference, _ServerMode +if TYPE_CHECKING: + from pymongo.asynchronous.client_session import AsyncClientSession + _IS_SYNC = False diff --git a/gridfs/synchronous/grid_file.py b/gridfs/synchronous/grid_file.py index 99b805e447..44cc097f7e 100644 --- a/gridfs/synchronous/grid_file.py +++ b/gridfs/synchronous/grid_file.py @@ -23,7 +23,7 @@ from collections import abc from collections.abc import Iterable, Mapping from types import TracebackType -from typing import Any, NoReturn, Self, cast +from typing import TYPE_CHECKING, Any, NoReturn, Self, cast from bson.int64 import Int64 from bson.objectid import ObjectId @@ -56,12 +56,14 @@ ) from pymongo.helpers_shared import _check_write_command_response from pymongo.read_preferences import ReadPreference, _ServerMode -from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.cursor import Cursor from pymongo.synchronous.database import Database from pymongo.synchronous.helpers import next +if TYPE_CHECKING: + from pymongo.synchronous.client_session import ClientSession + _IS_SYNC = True diff --git a/pymongo/_client_bulk_shared.py b/pymongo/_client_bulk_shared.py index bc47e93ff7..409b9d3411 100644 --- a/pymongo/_client_bulk_shared.py +++ b/pymongo/_client_bulk_shared.py @@ -30,10 +30,10 @@ from pymongo.errors import ClientBulkWriteException, OperationFailure from pymongo.helpers_shared import _get_wce_doc from pymongo.message import _ClientBulkWriteContext -from pymongo.write_concern import WriteConcern if TYPE_CHECKING: from pymongo.typings import _AgnosticMongoClient, _DocumentOut, _Pipeline + from pymongo.write_concern import WriteConcern def _merge_command( diff --git a/pymongo/asynchronous/_kms_connect.py b/pymongo/asynchronous/_kms_connect.py index 73e220cda4..768d279a0c 100644 --- a/pymongo/asynchronous/_kms_connect.py +++ b/pymongo/asynchronous/_kms_connect.py @@ -36,7 +36,6 @@ from pymongo.common import CONNECT_TIMEOUT from pymongo.errors import ConfigurationError from pymongo.helpers_shared import _get_timeout_details -from pymongo.pool_options import PoolOptions from pymongo.pool_shared import ( _async_configured_socket, _async_wrap_socket_tls, @@ -45,6 +44,7 @@ ) if TYPE_CHECKING: + from pymongo.pool_options import PoolOptions from pymongo.pyopenssl_context import _sslConn from pymongo.typings import _Address diff --git a/pymongo/asynchronous/bulk.py b/pymongo/asynchronous/bulk.py index d26ddb1dd0..f64fbe6ee0 100644 --- a/pymongo/asynchronous/bulk.py +++ b/pymongo/asynchronous/bulk.py @@ -29,7 +29,6 @@ from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none -from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.command_runner import ( run_bulk_write_command, ) @@ -57,6 +56,7 @@ from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection diff --git a/pymongo/asynchronous/client_bulk.py b/pymongo/asynchronous/client_bulk.py index 639eb66e5f..3727d56048 100644 --- a/pymongo/asynchronous/client_bulk.py +++ b/pymongo/asynchronous/client_bulk.py @@ -29,7 +29,6 @@ from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none -from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.command_cursor import AsyncCommandCursor from pymongo.asynchronous.command_runner import ( @@ -39,8 +38,10 @@ from pymongo.asynchronous.helpers import _handle_reauth if TYPE_CHECKING: + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection + from pymongo.write_concern import WriteConcern from pymongo._client_bulk_shared import ( _AgnosticClientBulkBase, _merge_command, @@ -68,7 +69,6 @@ InsertOneResult, UpdateResult, ) -from pymongo.write_concern import WriteConcern _IS_SYNC = False diff --git a/pymongo/asynchronous/client_session.py b/pymongo/asynchronous/client_session.py index 615e228671..23df3dda01 100644 --- a/pymongo/asynchronous/client_session.py +++ b/pymongo/asynchronous/client_session.py @@ -171,8 +171,6 @@ PyMongoError, WTimeoutError, ) -from pymongo.read_concern import ReadConcern -from pymongo.read_preferences import _ServerMode from pymongo.write_concern import WriteConcern if TYPE_CHECKING: @@ -180,6 +178,8 @@ from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection + from pymongo.read_concern import ReadConcern + from pymongo.read_preferences import _ServerMode _IS_SYNC = False diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index 25f819d5a7..29f82aeb3e 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -41,7 +41,6 @@ from bson.objectid import ObjectId from bson.raw_bson import RawBSONDocument from bson.son import SON -from bson.timestamp import Timestamp from pymongo import ASCENDING, _csot, common, helpers_shared, message from pymongo.asynchronous.aggregation import ( _CollectionAggregationCommand, @@ -125,6 +124,7 @@ class ReturnDocument: if TYPE_CHECKING: import bson + from bson.timestamp import Timestamp from pymongo.asynchronous.aggregation import _AggregationCommand from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.database import AsyncDatabase diff --git a/pymongo/asynchronous/database.py b/pymongo/asynchronous/database.py index 2b732ef159..589a467816 100644 --- a/pymongo/asynchronous/database.py +++ b/pymongo/asynchronous/database.py @@ -29,7 +29,6 @@ from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions from bson.dbref import DBRef -from bson.timestamp import Timestamp from pymongo import _csot, common from pymongo.asynchronous.aggregation import _DatabaseAggregationCommand from pymongo.asynchronous.change_stream import AsyncDatabaseChangeStream @@ -45,6 +44,7 @@ if TYPE_CHECKING: import bson import bson.codec_options + from bson.timestamp import Timestamp from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index 95d08a67bb..e12c001b68 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -50,10 +50,8 @@ from bson.codec_options import CodecOptions from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson from pymongo import _csot, _op_id -from pymongo._kms_connect_shared import AsyncKMSConnectCallback from pymongo.asynchronous._kms_connect import _KMS_CONNECT_TIMEOUT, _connect_kms from pymongo.asynchronous.collection import AsyncCollection -from pymongo.asynchronous.cursor import AsyncCursor from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.daemon import _spawn_daemon @@ -87,7 +85,6 @@ _raise_connection_failure, ) from pymongo.read_concern import ReadConcern -from pymongo.results import DeleteResult from pymongo.ssl_support import BLOCKING_IO_ERRORS, get_ssl_context from pymongo.typings import _DocumentType, _DocumentTypeArg from pymongo.uri_parser_shared import _parse_kms_tls_options, parse_host @@ -96,6 +93,10 @@ if TYPE_CHECKING: from pymongocrypt.mongocrypt import MongoCryptKmsContext + from pymongo._kms_connect_shared import AsyncKMSConnectCallback + from pymongo.asynchronous.cursor import AsyncCursor + from pymongo.results import DeleteResult + _IS_SYNC = False diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index 63aae88662..c6dbf175b9 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -60,7 +60,6 @@ ) from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, TypeRegistry -from bson.timestamp import Timestamp from pymongo import _csot, _op_id, common, helpers_shared, periodic_executor from pymongo.asynchronous import client_session, database, uri_parser from pymongo.asynchronous.change_stream import AsyncChangeStream, AsyncClusterChangeStream @@ -107,7 +106,6 @@ _Op, ) from pymongo.read_preferences import ReadPreference, _ServerMode -from pymongo.results import ClientBulkWriteResult from pymongo.server_description import ServerDescription from pymongo.server_selectors import writable_server_selector from pymongo.server_type import SERVER_TYPE @@ -136,6 +134,7 @@ from types import TracebackType from bson.objectid import ObjectId + from bson.timestamp import Timestamp from pymongo.asynchronous.bulk import _AsyncBulk from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.cursor_base import _ConnectionManager @@ -145,6 +144,7 @@ from pymongo.client_session_shared import _ServerSession from pymongo.read_concern import ReadConcern from pymongo.response import Response + from pymongo.results import ClientBulkWriteResult from pymongo.server_selectors import Selection diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 2f17aa2b2b..1d49a6ffb7 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -55,7 +55,9 @@ ConnectionClosedReason, ) from pymongo.network_layer import AsyncNetworkingInterface, async_receive_message, async_sendall -from pymongo.pool_options import PoolOptions + +# Needed for backwards-compatible imports from pool.py. +from pymongo.pool_options import PoolOptions # noqa: TC001 from pymongo.pool_shared import ( _UNDO_OPERATION_COUNT, _UNDO_PENDING, diff --git a/pymongo/asynchronous/settings.py b/pymongo/asynchronous/settings.py index ad70bd03e3..cb247ab48d 100644 --- a/pymongo/asynchronous/settings.py +++ b/pymongo/asynchronous/settings.py @@ -18,15 +18,18 @@ import threading from collections.abc import Callable, Collection +from typing import TYPE_CHECKING -from bson.objectid import ObjectId from pymongo import common from pymongo.asynchronous import monitor, pool from pymongo.asynchronous.pool import Pool from pymongo.common import LOCAL_THRESHOLD_MS, SERVER_SELECTION_TIMEOUT -from pymongo.pool_options import PoolOptions from pymongo.settings_shared import _BaseTopologySettings -from pymongo.topology_description import _ServerSelector + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.pool_options import PoolOptions + from pymongo.topology_description import _ServerSelector _IS_SYNC = False diff --git a/pymongo/change_stream_shared.py b/pymongo/change_stream_shared.py index 5ab2938385..23d5e09173 100644 --- a/pymongo/change_stream_shared.py +++ b/pymongo/change_stream_shared.py @@ -20,9 +20,7 @@ from collections.abc import Mapping from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast -from bson import CodecOptions from bson.raw_bson import RawBSONDocument -from bson.timestamp import Timestamp from pymongo import common from pymongo.collation import validate_collation_or_none from pymongo.errors import ( @@ -34,6 +32,8 @@ from pymongo.typings import _DocumentType if TYPE_CHECKING: + from bson import CodecOptions + from bson.timestamp import Timestamp from pymongo.typings import ( _AgnosticClientSession, _AgnosticCollection, diff --git a/pymongo/encryption_options.py b/pymongo/encryption_options.py index 1a78c70b43..70b371796a 100644 --- a/pymongo/encryption_options.py +++ b/pymongo/encryption_options.py @@ -39,7 +39,7 @@ AsyncKMSConnectCallback, HTTPProxyKMSConnect, KMSConnectCallback, - KMSConnectContext, + KMSConnectContext, # noqa: TC001 ) from pymongo.common import check_for_min_version, validate_is_mapping from pymongo.errors import ConfigurationError diff --git a/pymongo/encryption_shared.py b/pymongo/encryption_shared.py index e0c23b6773..b09eef9c2f 100644 --- a/pymongo/encryption_shared.py +++ b/pymongo/encryption_shared.py @@ -19,7 +19,7 @@ import contextlib import enum from collections.abc import Iterator -from typing import Any +from typing import TYPE_CHECKING, Any try: from pymongocrypt.mongocrypt import MongoCryptOptions # type:ignore[import-untyped] @@ -28,7 +28,9 @@ from bson.errors import BSONError from pymongo.errors import EncryptionError -from pymongo.results import BulkWriteResult + +if TYPE_CHECKING: + from pymongo.results import BulkWriteResult @contextlib.contextmanager diff --git a/pymongo/hello.py b/pymongo/hello.py index e6e97bfbae..2fac9f34af 100644 --- a/pymongo/hello.py +++ b/pymongo/hello.py @@ -20,13 +20,15 @@ import datetime import itertools from collections.abc import Mapping -from typing import Any, Generic +from typing import TYPE_CHECKING, Any, Generic -from bson.objectid import ObjectId from pymongo import common from pymongo.server_type import SERVER_TYPE from pymongo.typings import ClusterTime, _DocumentType +if TYPE_CHECKING: + from bson.objectid import ObjectId + def _get_server_type(doc: Mapping[str, Any]) -> int: """Determine the server type from a hello response.""" diff --git a/pymongo/message.py b/pymongo/message.py index d89b467a4a..7cecf217a3 100644 --- a/pymongo/message.py +++ b/pymongo/message.py @@ -42,7 +42,6 @@ _inflate_bson, ) from pymongo.common import MONGOS_EXHAUST_WIRE_VERSION -from pymongo.monitoring import _EventListeners try: from pymongo import _cmessage # type: ignore[attr-defined] @@ -59,6 +58,7 @@ if TYPE_CHECKING: from pymongo.compression_support import SnappyContext, ZlibContext, ZstdContext + from pymongo.monitoring import _EventListeners from pymongo.read_concern import ReadConcern from pymongo.typings import ( _Address, diff --git a/pymongo/monitoring.py b/pymongo/monitoring.py index 57bd34d08c..98caff0088 100644 --- a/pymongo/monitoring.py +++ b/pymongo/monitoring.py @@ -193,16 +193,16 @@ def connection_checked_in(self, event): from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING, Any -from bson.objectid import ObjectId from pymongo.hello import Hello, HelloCompat from pymongo.helpers_shared import _SENSITIVE_COMMANDS, _handle_exception -from pymongo.typings import _Address, _DocumentOut if TYPE_CHECKING: from datetime import timedelta + from bson.objectid import ObjectId from pymongo.server_description import ServerDescription from pymongo.topology_description import TopologyDescription + from pymongo.typings import _Address, _DocumentOut _Listeners = namedtuple( diff --git a/pymongo/operations.py b/pymongo/operations.py index 272c37c42c..1a737c05fc 100644 --- a/pymongo/operations.py +++ b/pymongo/operations.py @@ -28,7 +28,6 @@ cast, ) -from bson.raw_bson import RawBSONDocument from pymongo import helpers_shared from pymongo.collation import validate_collation_or_none from pymongo.common import validate_is_mapping, validate_list @@ -38,6 +37,7 @@ from pymongo.write_concern import validate_boolean if TYPE_CHECKING: + from bson.raw_bson import RawBSONDocument from pymongo.typings import _AgnosticBulk, _AgnosticClientBulk diff --git a/pymongo/pool_shared.py b/pymongo/pool_shared.py index 040b62a4e8..71cfc4d3b4 100644 --- a/pymongo/pool_shared.py +++ b/pymongo/pool_shared.py @@ -39,7 +39,6 @@ from pymongo import _csot from pymongo._telemetry import _CmapTelemetry from pymongo.asynchronous.helpers import _getaddrinfo -from pymongo.auth_shared import _AuthContext from pymongo.common import MAX_BSON_SIZE, MAX_MESSAGE_SIZE, MAX_WIRE_VERSION, MAX_WRITE_BATCH_SIZE from pymongo.errors import ( # type:ignore[attr-defined] AutoReconnect, @@ -61,7 +60,6 @@ NetworkingInterfaceBase, PyMongoProtocol, ) -from pymongo.pool_options import PoolOptions from pymongo.server_api import _add_to_command from pymongo.socket_checker import SocketChecker from pymongo.ssl_support import SSL_EOF_ERRORS, PYSSLError, SSLError, _has_sni @@ -69,7 +67,9 @@ SSLErrors = (PYSSLError, SSLError) if TYPE_CHECKING: from bson.objectid import ObjectId + from pymongo.auth_shared import _AuthContext from pymongo.compression_support import SnappyContext, ZlibContext, ZstdContext + from pymongo.pool_options import PoolOptions from pymongo.pyopenssl_context import _sslConn from pymongo.typings import _Address, _AgnosticClientSession, _AgnosticMongoClient diff --git a/pymongo/server_description.py b/pymongo/server_description.py index 836436e450..c82fc6d8f6 100644 --- a/pymongo/server_description.py +++ b/pymongo/server_description.py @@ -22,13 +22,15 @@ import time import warnings from collections.abc import Mapping -from typing import Any +from typing import TYPE_CHECKING, Any from bson import EPOCH_NAIVE -from bson.objectid import ObjectId from pymongo.hello import Hello from pymongo.server_type import SERVER_TYPE -from pymongo.typings import ClusterTime, _Address + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.typings import ClusterTime, _Address class ServerDescription: diff --git a/pymongo/synchronous/_kms_connect.py b/pymongo/synchronous/_kms_connect.py index 06d5be379f..3ebef0cc2c 100644 --- a/pymongo/synchronous/_kms_connect.py +++ b/pymongo/synchronous/_kms_connect.py @@ -36,7 +36,6 @@ from pymongo.common import CONNECT_TIMEOUT from pymongo.errors import ConfigurationError from pymongo.helpers_shared import _get_timeout_details -from pymongo.pool_options import PoolOptions from pymongo.pool_shared import ( _close_late_socket, _configured_socket, @@ -45,6 +44,7 @@ ) if TYPE_CHECKING: + from pymongo.pool_options import PoolOptions from pymongo.pyopenssl_context import _sslConn from pymongo.typings import _Address diff --git a/pymongo/synchronous/bulk.py b/pymongo/synchronous/bulk.py index ab50a96522..c341693a36 100644 --- a/pymongo/synchronous/bulk.py +++ b/pymongo/synchronous/bulk.py @@ -49,7 +49,6 @@ _EncryptedBulkWriteContext, ) from pymongo.read_preferences import ReadPreference -from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.command_runner import ( run_bulk_write_command, ) @@ -57,6 +56,7 @@ from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection diff --git a/pymongo/synchronous/client_bulk.py b/pymongo/synchronous/client_bulk.py index b649313932..2c5d0050eb 100644 --- a/pymongo/synchronous/client_bulk.py +++ b/pymongo/synchronous/client_bulk.py @@ -29,7 +29,6 @@ from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none -from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.command_cursor import CommandCursor from pymongo.synchronous.command_runner import ( @@ -39,8 +38,10 @@ from pymongo.synchronous.helpers import _handle_reauth if TYPE_CHECKING: + from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection + from pymongo.write_concern import WriteConcern from pymongo._client_bulk_shared import ( _AgnosticClientBulkBase, _merge_command, @@ -68,7 +69,6 @@ InsertOneResult, UpdateResult, ) -from pymongo.write_concern import WriteConcern _IS_SYNC = True diff --git a/pymongo/synchronous/client_session.py b/pymongo/synchronous/client_session.py index ba7ee39450..0c038561d7 100644 --- a/pymongo/synchronous/client_session.py +++ b/pymongo/synchronous/client_session.py @@ -169,14 +169,14 @@ PyMongoError, WTimeoutError, ) -from pymongo.read_concern import ReadConcern -from pymongo.read_preferences import _ServerMode from pymongo.synchronous.cursor_base import _ConnectionManager from pymongo.write_concern import WriteConcern if TYPE_CHECKING: from types import TracebackType + from pymongo.read_concern import ReadConcern + from pymongo.read_preferences import _ServerMode from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index 6fbed057bf..34a2d1e245 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -40,7 +40,6 @@ from bson.objectid import ObjectId from bson.raw_bson import RawBSONDocument from bson.son import SON -from bson.timestamp import Timestamp from pymongo import ASCENDING, _csot, common, helpers_shared, message from pymongo.collation import validate_collation_or_none from pymongo.common import _ecoc_coll_name, _esc_coll_name @@ -124,6 +123,7 @@ class ReturnDocument: if TYPE_CHECKING: import bson + from bson.timestamp import Timestamp from pymongo.collation import Collation from pymongo.read_concern import ReadConcern from pymongo.synchronous.aggregation import _AggregationCommand diff --git a/pymongo/synchronous/database.py b/pymongo/synchronous/database.py index 1346371ab4..49aff61619 100644 --- a/pymongo/synchronous/database.py +++ b/pymongo/synchronous/database.py @@ -29,7 +29,6 @@ from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions from bson.dbref import DBRef -from bson.timestamp import Timestamp from pymongo import _csot, common from pymongo.common import _ecoc_coll_name, _esc_coll_name from pymongo.database_shared import _check_name, _CodecDocumentType @@ -45,6 +44,7 @@ if TYPE_CHECKING: import bson import bson.codec_options + from bson.timestamp import Timestamp from pymongo.read_concern import ReadConcern from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.mongo_client import MongoClient diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 4eb9df0228..0cea32c29a 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -49,7 +49,6 @@ from bson.codec_options import CodecOptions from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson from pymongo import _csot, _op_id -from pymongo._kms_connect_shared import KMSConnectCallback from pymongo.daemon import _spawn_daemon from pymongo.encryption_options import ( AutoEncryptionOpts, @@ -81,11 +80,9 @@ _raise_connection_failure, ) from pymongo.read_concern import ReadConcern -from pymongo.results import DeleteResult 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.cursor import Cursor from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient from pymongo.typings import _DocumentType, _DocumentTypeArg @@ -95,6 +92,10 @@ if TYPE_CHECKING: from pymongocrypt.mongocrypt import MongoCryptKmsContext + from pymongo._kms_connect_shared import KMSConnectCallback + from pymongo.results import DeleteResult + from pymongo.synchronous.cursor import Cursor + _IS_SYNC = True diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index cebc6a5e94..825ca41e81 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -59,7 +59,6 @@ ) from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, TypeRegistry -from bson.timestamp import Timestamp from pymongo import _csot, _op_id, common, helpers_shared, periodic_executor from pymongo.client_options import ClientOptions from pymongo.client_session_shared import SessionOptions, TransactionOptions, _EmptyServerSession @@ -99,7 +98,6 @@ _Op, ) from pymongo.read_preferences import ReadPreference, _ServerMode -from pymongo.results import ClientBulkWriteResult from pymongo.server_description import ServerDescription from pymongo.server_selectors import writable_server_selector from pymongo.server_type import SERVER_TYPE @@ -135,9 +133,11 @@ from types import TracebackType from bson.objectid import ObjectId + from bson.timestamp import Timestamp from pymongo.client_session_shared import _ServerSession from pymongo.read_concern import ReadConcern from pymongo.response import Response + from pymongo.results import ClientBulkWriteResult from pymongo.server_selectors import Selection from pymongo.synchronous.bulk import _Bulk from pymongo.synchronous.client_session import ClientSession diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index f746631616..ebb03dfeb2 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -53,7 +53,9 @@ ConnectionClosedReason, ) from pymongo.network_layer import NetworkingInterface, receive_message, sendall -from pymongo.pool_options import PoolOptions + +# Needed for backwards-compatible imports from pool.py. +from pymongo.pool_options import PoolOptions # noqa: TC001 from pymongo.pool_shared import ( _UNDO_OPERATION_COUNT, _UNDO_PENDING, diff --git a/pymongo/synchronous/settings.py b/pymongo/synchronous/settings.py index c6a0187276..301d7ca77d 100644 --- a/pymongo/synchronous/settings.py +++ b/pymongo/synchronous/settings.py @@ -18,15 +18,18 @@ import threading from collections.abc import Callable, Collection +from typing import TYPE_CHECKING -from bson.objectid import ObjectId from pymongo import common from pymongo.common import LOCAL_THRESHOLD_MS, SERVER_SELECTION_TIMEOUT -from pymongo.pool_options import PoolOptions from pymongo.settings_shared import _BaseTopologySettings from pymongo.synchronous import monitor, pool from pymongo.synchronous.pool import Pool -from pymongo.topology_description import _ServerSelector + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.pool_options import PoolOptions + from pymongo.topology_description import _ServerSelector _IS_SYNC = True diff --git a/pymongo/topology_description.py b/pymongo/topology_description.py index 649a20c380..47f00addf3 100644 --- a/pymongo/topology_description.py +++ b/pymongo/topology_description.py @@ -22,20 +22,23 @@ from collections.abc import Callable, Mapping, MutableMapping from random import sample from typing import ( + TYPE_CHECKING, Any, NamedTuple, cast, ) from bson.min_key import MinKey -from bson.objectid import ObjectId from pymongo import common from pymongo.errors import ConfigurationError, PyMongoError from pymongo.read_preferences import Primary, ReadPreference, _AggWritePref, _ServerMode from pymongo.server_description import ServerDescription from pymongo.server_selectors import Selection from pymongo.server_type import SERVER_TYPE -from pymongo.typings import _Address + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.typings import _Address # Enumeration for various kinds of MongoDB cluster topologies. diff --git a/pymongo/uri_parser_shared.py b/pymongo/uri_parser_shared.py index e6775b8668..cf5037b101 100644 --- a/pymongo/uri_parser_shared.py +++ b/pymongo/uri_parser_shared.py @@ -39,10 +39,10 @@ get_validated_options, ) from pymongo.errors import ConfigurationError, InvalidURI -from pymongo.typings import _Address if TYPE_CHECKING: from pymongo.pyopenssl_context import SSLContext + from pymongo.typings import _Address SCHEME = "mongodb://" diff --git a/pyproject.toml b/pyproject.toml index 871939af25..f8542ef725 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -218,6 +218,7 @@ extend-select = [ "YTT", # flake8-2020 "EXE", # flake8-executable "ASYNC", # flake8-async + "TC001", # flake8-type-checking: typing-only first-party imports ] ignore = [ "PLR", # Design related pylint codes diff --git a/test/__init__.py b/test/__init__.py index 2220bf3661..2d3bc76e5d 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -46,7 +46,7 @@ from collections.abc import Callable, Generator from contextlib import contextmanager from functools import partial, wraps -from typing import Any, overload +from typing import TYPE_CHECKING, Any, overload from unittest import SkipTest from urllib.parse import quote_plus @@ -57,7 +57,6 @@ from pymongo.hello import HelloCompat from pymongo.server_api import ServerApi from pymongo.ssl_support import HAVE_SSL, _ssl # type:ignore[attr-defined] -from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient sys.path[0:0] = [""] @@ -84,6 +83,9 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + _IS_SYNC = True diff --git a/test/asynchronous/__init__.py b/test/asynchronous/__init__.py index 57ee8e9a99..59b3168048 100644 --- a/test/asynchronous/__init__.py +++ b/test/asynchronous/__init__.py @@ -46,14 +46,13 @@ from collections.abc import Callable, Generator from contextlib import asynccontextmanager, contextmanager from functools import partial, wraps -from typing import Any, overload +from typing import TYPE_CHECKING, Any, overload from unittest import SkipTest from urllib.parse import quote_plus import pymongo import pymongo.errors from bson.son import SON -from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.common import partition_node from pymongo.hello import HelloCompat @@ -84,6 +83,9 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + _IS_SYNC = False diff --git a/test/asynchronous/test_bulk.py b/test/asynchronous/test_bulk.py index d39e6cb3a5..51f447ed30 100644 --- a/test/asynchronous/test_bulk.py +++ b/test/asynchronous/test_bulk.py @@ -18,16 +18,13 @@ import sys import uuid -from typing import Any, Optional - -from pymongo.asynchronous.mongo_client import AsyncMongoClient +from typing import TYPE_CHECKING, Any sys.path[0:0] = [""] from bson.binary import Binary, UuidRepresentation from bson.codec_options import CodecOptions from bson.objectid import ObjectId -from pymongo.asynchronous.collection import AsyncCollection from pymongo.common import partition_node from pymongo.errors import BulkWriteError, ConfigurationError, InvalidOperation, OperationFailure from pymongo.operations import * @@ -35,6 +32,10 @@ from test.asynchronous import AsyncIntegrationTest, async_client_context, remove_all_users, unittest from test.utils_shared import async_wait_until +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + from pymongo.asynchronous.mongo_client import AsyncMongoClient + _IS_SYNC = False diff --git a/test/asynchronous/test_client_metadata.py b/test/asynchronous/test_client_metadata.py index da36c9752f..afc1aac1a3 100644 --- a/test/asynchronous/test_client_metadata.py +++ b/test/asynchronous/test_client_metadata.py @@ -18,17 +18,19 @@ import pathlib import time import unittest -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast import pytest -from pymongo import AsyncMongoClient from pymongo.driver_info import DriverInfo from pymongo.monitoring import ConnectionClosedEvent from test.asynchronous import AsyncIntegrationTest from test.asynchronous.unified_format import generate_test_classes, get_test_path from test.utils_shared import CMAPListener +if TYPE_CHECKING: + from pymongo import AsyncMongoClient + try: from mockupdb import MockupDB, OpMsgReply diff --git a/test/asynchronous/test_collection.py b/test/asynchronous/test_collection.py index 0a0fa823db..5c378d9bf0 100644 --- a/test/asynchronous/test_collection.py +++ b/test/asynchronous/test_collection.py @@ -23,9 +23,8 @@ from codecs import utf_8_decode from collections import defaultdict from collections.abc import Iterable -from typing import Any, no_type_check +from typing import TYPE_CHECKING, Any, no_type_check -from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.helpers import anext from test.asynchronous.utils import async_get_pool @@ -40,7 +39,6 @@ from pymongo import ASCENDING, DESCENDING, GEO2D, GEOSPHERE, HASHED, TEXT from pymongo.asynchronous.collection import AsyncCollection, ReturnDocument from pymongo.asynchronous.command_cursor import AsyncCommandCursor -from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.bulk_shared import BulkWriteError from pymongo.cursor_shared import CursorType from pymongo.errors import ( @@ -79,6 +77,10 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + from pymongo.asynchronous.mongo_client import AsyncMongoClient + _IS_SYNC = False diff --git a/test/asynchronous/test_connections_survive_primary_stepdown_spec.py b/test/asynchronous/test_connections_survive_primary_stepdown_spec.py index f3b729316e..889605c594 100644 --- a/test/asynchronous/test_connections_survive_primary_stepdown_spec.py +++ b/test/asynchronous/test_connections_survive_primary_stepdown_spec.py @@ -22,9 +22,10 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson import SON from pymongo import monitoring -from pymongo.asynchronous.collection import AsyncCollection from pymongo.errors import NotPrimaryError from pymongo.write_concern import WriteConcern from test.asynchronous import ( @@ -37,6 +38,9 @@ CMAPListener, ) +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + _IS_SYNC = False diff --git a/test/asynchronous/test_cursor.py b/test/asynchronous/test_cursor.py index 2bd45c00b8..178b08bc6a 100644 --- a/test/asynchronous/test_cursor.py +++ b/test/asynchronous/test_cursor.py @@ -26,7 +26,7 @@ import sys import threading import time -from typing import Any +from typing import TYPE_CHECKING, Any import pymongo @@ -40,7 +40,6 @@ from pymongo.asynchronous.helpers import anext from pymongo.collation import Collation from pymongo.errors import ExecutionTimeout, InvalidOperation, OperationFailure, PyMongoError -from pymongo.operations import _IndexList from pymongo.read_concern import ReadConcern from pymongo.read_preferences import ReadPreference from pymongo.write_concern import WriteConcern @@ -55,6 +54,9 @@ ignore_deprecations, ) +if TYPE_CHECKING: + from pymongo.operations import _IndexList + _IS_SYNC = False diff --git a/test/asynchronous/test_encryption.py b/test/asynchronous/test_encryption.py index 535d56d779..d8dc3530e5 100644 --- a/test/asynchronous/test_encryption.py +++ b/test/asynchronous/test_encryption.py @@ -33,11 +33,10 @@ import warnings from collections.abc import Mapping from threading import Thread -from typing import Any, Optional +from typing import TYPE_CHECKING, Any import pytest -from pymongo.asynchronous.collection import AsyncCollection from pymongo.daemon import _spawn_daemon from pymongo.uri_parser_shared import _parse_kms_tls_options from test.asynchronous import AsyncIntegrationTest, AsyncPyMongoTestCase, async_client_context @@ -115,6 +114,9 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + _IS_SYNC = False pytestmark = pytest.mark.encryption diff --git a/test/asynchronous/test_grid_file.py b/test/asynchronous/test_grid_file.py index 5319620624..9293725c83 100644 --- a/test/asynchronous/test_grid_file.py +++ b/test/asynchronous/test_grid_file.py @@ -23,7 +23,6 @@ import zipfile from io import BytesIO -from pymongo.asynchronous.database import AsyncDatabase from test.asynchronous import ( AsyncIntegrationTest, AsyncUnitTest, @@ -34,6 +33,8 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.objectid import ObjectId from gridfs.asynchronous.grid_file import ( _SEEK_CUR, @@ -51,6 +52,9 @@ from pymongo.message import _CursorAddress from test.utils_shared import OvertCommandListener +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + _IS_SYNC = False diff --git a/test/asynchronous/test_gridfs.py b/test/asynchronous/test_gridfs.py index 81aa1b6e8e..6b1c1c9460 100644 --- a/test/asynchronous/test_gridfs.py +++ b/test/asynchronous/test_gridfs.py @@ -29,11 +29,12 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + import gridfs from bson.binary import Binary from gridfs.asynchronous.grid_file import DEFAULT_CHUNK_SIZE, AsyncGridOutCursor from gridfs.errors import CorruptGridFile, FileExists, NoFile -from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.errors import ( ConfigurationError, @@ -45,6 +46,9 @@ from test.asynchronous.utils import async_joinall from test.utils_shared import one +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + _IS_SYNC = False diff --git a/test/asynchronous/test_sdam_monitoring_spec.py b/test/asynchronous/test_sdam_monitoring_spec.py index 33e81d672c..9fc83bdff5 100644 --- a/test/asynchronous/test_sdam_monitoring_spec.py +++ b/test/asynchronous/test_sdam_monitoring_spec.py @@ -25,9 +25,10 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.json_util import object_hook from pymongo import AsyncMongoClient, monitoring -from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.monitor import Monitor from pymongo.common import clean_node from pymongo.errors import ConnectionFailure, NotPrimaryError @@ -41,6 +42,9 @@ server_name_to_type, ) +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + _IS_SYNC = False # Location of JSON test specifications. diff --git a/test/asynchronous/test_sfp.py b/test/asynchronous/test_sfp.py index d9b6350002..3b1a70f026 100644 --- a/test/asynchronous/test_sfp.py +++ b/test/asynchronous/test_sfp.py @@ -19,17 +19,19 @@ import os import sys import unittest -from typing import Any +from typing import TYPE_CHECKING, Any import pytest sys.path[0:0] = [""] from bson import ObjectId -from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.server_api import ServerApi from test.asynchronous import AsyncPyMongoTestCase +if TYPE_CHECKING: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + _IS_SYNC = False pytestmark = pytest.mark.sfp diff --git a/test/asynchronous/unified_format.py b/test/asynchronous/unified_format.py index 94ce837726..3a21c664a0 100644 --- a/test/asynchronous/unified_format.py +++ b/test/asynchronous/unified_format.py @@ -34,14 +34,13 @@ from collections.abc import Mapping from inspect import iscoroutinefunction from pathlib import Path -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, Optional import pytest import pymongo from bson import SON, json_util from bson.codec_options import DEFAULT_CODEC_OPTIONS -from bson.objectid import ObjectId from gridfs import AsyncGridFSBucket, GridOut, NoFile from gridfs.errors import CorruptGridFile from pymongo import ASCENDING, AsyncMongoClient, CursorType, _csot @@ -79,7 +78,6 @@ from pymongo.server_selectors import Selection, writable_server_selector from pymongo.server_type import SERVER_TYPE from pymongo.topology_description import TopologyDescription -from pymongo.typings import _Address from pymongo.write_concern import WriteConcern from test.asynchronous import ( AsyncIntegrationTest, @@ -113,6 +111,10 @@ ) from test.version import Version +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.typings import _Address + _IS_SYNC = False IS_INTERRUPTED = False diff --git a/test/asynchronous/utils.py b/test/asynchronous/utils.py index 3e6669a753..8eea5c8157 100644 --- a/test/asynchronous/utils.py +++ b/test/asynchronous/utils.py @@ -27,10 +27,9 @@ import unittest from functools import wraps from inspect import iscoroutinefunction +from typing import TYPE_CHECKING from bson.son import SON -from pymongo import AsyncMongoClient -from pymongo.asynchronous.pool import Pool from pymongo.errors import ConfigurationError from pymongo.hello import HelloCompat from pymongo.lock import _async_create_lock @@ -39,6 +38,10 @@ from pymongo.read_preferences import ReadPreference from pymongo.server_selectors import any_server_selector, writable_server_selector +if TYPE_CHECKING: + from pymongo import AsyncMongoClient + from pymongo.asynchronous.pool import Pool + _IS_SYNC = False diff --git a/test/mockupdb/test_cursor_namespace.py b/test/mockupdb/test_cursor_namespace.py index 7cf0048bd9..8d7dfb8c9b 100644 --- a/test/mockupdb/test_cursor_namespace.py +++ b/test/mockupdb/test_cursor_namespace.py @@ -30,9 +30,13 @@ _HAVE_MOCKUPDB = False -from pymongo import MongoClient +from typing import TYPE_CHECKING + from pymongo.common import MIN_SUPPORTED_WIRE_VERSION +if TYPE_CHECKING: + from pymongo import MongoClient + pytestmark = pytest.mark.mockupdb diff --git a/test/test_bulk.py b/test/test_bulk.py index d1ec4c7c83..15035f4783 100644 --- a/test/test_bulk.py +++ b/test/test_bulk.py @@ -18,9 +18,7 @@ import sys import uuid -from typing import Any, Optional - -from pymongo.synchronous.mongo_client import MongoClient +from typing import TYPE_CHECKING, Any sys.path[0:0] = [""] @@ -30,11 +28,14 @@ from pymongo.common import partition_node from pymongo.errors import BulkWriteError, ConfigurationError, InvalidOperation, OperationFailure from pymongo.operations import * -from pymongo.synchronous.collection import Collection from pymongo.write_concern import WriteConcern from test import IntegrationTest, client_context, remove_all_users, unittest from test.utils_shared import wait_until +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + from pymongo.synchronous.mongo_client import MongoClient + _IS_SYNC = True diff --git a/test/test_client_metadata.py b/test/test_client_metadata.py index 7b9e62426c..e1c53513cd 100644 --- a/test/test_client_metadata.py +++ b/test/test_client_metadata.py @@ -18,17 +18,19 @@ import pathlib import time import unittest -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast import pytest -from pymongo import MongoClient from pymongo.driver_info import DriverInfo from pymongo.monitoring import ConnectionClosedEvent from test import IntegrationTest from test.unified_format import generate_test_classes, get_test_path from test.utils_shared import CMAPListener +if TYPE_CHECKING: + from pymongo import MongoClient + try: from mockupdb import MockupDB, OpMsgReply diff --git a/test/test_collection.py b/test/test_collection.py index 0732605dd7..db6f5f9fb7 100644 --- a/test/test_collection.py +++ b/test/test_collection.py @@ -23,9 +23,8 @@ from codecs import utf_8_decode from collections import defaultdict from collections.abc import Iterable -from typing import Any, no_type_check +from typing import TYPE_CHECKING, Any, no_type_check -from pymongo.synchronous.database import Database from pymongo.synchronous.helpers import next from test.utils import get_pool @@ -63,7 +62,6 @@ ) from pymongo.synchronous.collection import Collection, ReturnDocument from pymongo.synchronous.command_cursor import CommandCursor -from pymongo.synchronous.mongo_client import MongoClient from pymongo.write_concern import WriteConcern from test import ( # TODO: fix sync imports in PYTHON-4528 IntegrationTest, @@ -79,6 +77,10 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + from pymongo.synchronous.mongo_client import MongoClient + _IS_SYNC = True diff --git a/test/test_connections_survive_primary_stepdown_spec.py b/test/test_connections_survive_primary_stepdown_spec.py index dfcec79322..e704914267 100644 --- a/test/test_connections_survive_primary_stepdown_spec.py +++ b/test/test_connections_survive_primary_stepdown_spec.py @@ -22,10 +22,11 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson import SON from pymongo import monitoring from pymongo.errors import NotPrimaryError -from pymongo.synchronous.collection import Collection from pymongo.write_concern import WriteConcern from test import ( IntegrationTest, @@ -37,6 +38,9 @@ CMAPListener, ) +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + _IS_SYNC = True diff --git a/test/test_cursor.py b/test/test_cursor.py index c229129a30..af7ff17214 100644 --- a/test/test_cursor.py +++ b/test/test_cursor.py @@ -26,7 +26,7 @@ import sys import threading import time -from typing import Any +from typing import TYPE_CHECKING, Any import pymongo @@ -38,7 +38,6 @@ from pymongo import ASCENDING, DESCENDING from pymongo.collation import Collation from pymongo.errors import ExecutionTimeout, InvalidOperation, OperationFailure, PyMongoError -from pymongo.operations import _IndexList from pymongo.read_concern import ReadConcern from pymongo.read_preferences import ReadPreference from pymongo.synchronous.cursor import Cursor, CursorType @@ -55,6 +54,9 @@ wait_until, ) +if TYPE_CHECKING: + from pymongo.operations import _IndexList + _IS_SYNC = True diff --git a/test/test_encryption.py b/test/test_encryption.py index c7717737d4..815203eac5 100644 --- a/test/test_encryption.py +++ b/test/test_encryption.py @@ -33,12 +33,11 @@ import warnings from collections.abc import Mapping from threading import Thread -from typing import Any, Optional +from typing import TYPE_CHECKING, Any import pytest from pymongo.daemon import _spawn_daemon -from pymongo.synchronous.collection import Collection from pymongo.uri_parser_shared import _parse_kms_tls_options from test import IntegrationTest, PyMongoTestCase, client_context from test.test_bulk import BulkTestBase @@ -115,6 +114,9 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + _IS_SYNC = True pytestmark = pytest.mark.encryption diff --git a/test/test_grid_file.py b/test/test_grid_file.py index 21c2c29d74..c83166cc77 100644 --- a/test/test_grid_file.py +++ b/test/test_grid_file.py @@ -23,7 +23,6 @@ import zipfile from io import BytesIO -from pymongo.synchronous.database import Database from test import ( IntegrationTest, UnitTest, @@ -34,6 +33,8 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.objectid import ObjectId from gridfs.errors import NoFile from gridfs.synchronous.grid_file import ( @@ -51,6 +52,9 @@ from pymongo.synchronous.helpers import iter, next from test.utils_shared import OvertCommandListener +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + _IS_SYNC = True diff --git a/test/test_gridfs.py b/test/test_gridfs.py index ab6a8f969a..6371fd2019 100644 --- a/test/test_gridfs.py +++ b/test/test_gridfs.py @@ -29,6 +29,8 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + import gridfs from bson.binary import Binary from gridfs.errors import CorruptGridFile, FileExists, NoFile @@ -39,12 +41,14 @@ ServerSelectionTimeoutError, ) from pymongo.read_preferences import ReadPreference -from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient from test import IntegrationTest, client_context, unittest from test.utils import joinall from test.utils_shared import one +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + _IS_SYNC = True diff --git a/test/test_sdam_monitoring_spec.py b/test/test_sdam_monitoring_spec.py index 95ce620139..ebdb9fa82d 100644 --- a/test/test_sdam_monitoring_spec.py +++ b/test/test_sdam_monitoring_spec.py @@ -25,13 +25,14 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.json_util import object_hook from pymongo import MongoClient, monitoring from pymongo.common import clean_node from pymongo.errors import ConnectionFailure, NotPrimaryError from pymongo.hello import Hello from pymongo.server_description import ServerDescription -from pymongo.synchronous.collection import Collection from pymongo.synchronous.monitor import Monitor from pymongo.topology_description import TOPOLOGY_TYPE from test import IntegrationTest, client_context, client_knobs, unittest @@ -41,6 +42,9 @@ wait_until, ) +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + _IS_SYNC = True # Location of JSON test specifications. diff --git a/test/test_sfp.py b/test/test_sfp.py index b5dcfa5cc7..3ccf968af6 100644 --- a/test/test_sfp.py +++ b/test/test_sfp.py @@ -19,7 +19,7 @@ import os import sys import unittest -from typing import Any +from typing import TYPE_CHECKING, Any import pytest @@ -27,9 +27,11 @@ from bson import ObjectId from pymongo.server_api import ServerApi -from pymongo.synchronous.mongo_client import MongoClient from test import PyMongoTestCase +if TYPE_CHECKING: + from pymongo.synchronous.mongo_client import MongoClient + _IS_SYNC = True pytestmark = pytest.mark.sfp diff --git a/test/test_topology.py b/test/test_topology.py index a767b4fa24..0dd0f90f78 100644 --- a/test/test_topology.py +++ b/test/test_topology.py @@ -26,12 +26,12 @@ from pymongo import common from pymongo.errors import AutoReconnect, ConfigurationError, ConnectionFailure from pymongo.hello import Hello, HelloCompat +from pymongo.pool_options import PoolOptions from pymongo.read_preferences import Primary, ReadPreference, Secondary from pymongo.server_description import ServerDescription from pymongo.server_selectors import any_server_selector, writable_server_selector from pymongo.server_type import SERVER_TYPE from pymongo.synchronous.monitor import Monitor -from pymongo.synchronous.pool import PoolOptions from pymongo.synchronous.server import Server from pymongo.synchronous.settings import TopologySettings from pymongo.synchronous.topology import Topology diff --git a/test/test_typing.py b/test/test_typing.py index 93a899fcd8..546f732f8d 100644 --- a/test/test_typing.py +++ b/test/test_typing.py @@ -37,6 +37,7 @@ from bson import Binary, ObjectId # noqa: TC004 from bson.binary import BinaryVector, BinaryVectorDtype # noqa: TC004 + from pymongo.synchronous.collection import Collection class Movie(TypedDict): name: str @@ -70,7 +71,6 @@ class ImplicitMovie(TypedDict): from pymongo import ASCENDING, MongoClient from pymongo.operations import DeleteOne, InsertOne, ReplaceOne from pymongo.read_preferences import ReadPreference -from pymongo.synchronous.collection import Collection from pymongo.synchronous.cursor import Cursor from test import IntegrationTest, PyMongoTestCase, client_context diff --git a/test/unified_format.py b/test/unified_format.py index f39e97365e..8b6f7c60de 100644 --- a/test/unified_format.py +++ b/test/unified_format.py @@ -34,14 +34,13 @@ from collections.abc import Mapping from inspect import iscoroutinefunction from pathlib import Path -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, Optional import pytest import pymongo from bson import SON, json_util from bson.codec_options import DEFAULT_CODEC_OPTIONS -from bson.objectid import ObjectId from gridfs import GridFSBucket, GridOut, NoFile from gridfs.errors import CorruptGridFile from pymongo import ASCENDING, CursorType, MongoClient, _csot @@ -79,7 +78,6 @@ from pymongo.synchronous.encryption import ClientEncryption from pymongo.synchronous.helpers import next from pymongo.topology_description import TopologyDescription -from pymongo.typings import _Address from pymongo.write_concern import WriteConcern from test import ( IntegrationTest, @@ -112,6 +110,10 @@ from test.utils_spec_runner import SpecRunnerThread from test.version import Version +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.typings import _Address + _IS_SYNC = True IS_INTERRUPTED = False diff --git a/test/unified_format_shared.py b/test/unified_format_shared.py index b3b8e28a3a..311d9fcd01 100644 --- a/test/unified_format_shared.py +++ b/test/unified_format_shared.py @@ -27,7 +27,7 @@ import types from collections import abc from collections.abc import MutableMapping -from typing import Any +from typing import TYPE_CHECKING, Any from bson import ( RE_TYPE, @@ -79,8 +79,6 @@ _ServerHeartbeatEvent, ) from pymongo.results import BulkWriteResult -from pymongo.server_description import ServerDescription -from pymongo.topology_description import TopologyDescription from test.helpers_shared import ( AWS_CREDS, AWS_CREDS_2, @@ -94,6 +92,10 @@ ) from test.utils_shared import CMAPListener, camel_to_snake, parse_collection_options +if TYPE_CHECKING: + from pymongo.server_description import ServerDescription + from pymongo.topology_description import TopologyDescription + JSON_OPTS = json_util.JSONOptions(tz_aware=False) IS_INTERRUPTED = False diff --git a/test/utils.py b/test/utils.py index e52fd336e2..6f9c05e504 100644 --- a/test/utils.py +++ b/test/utils.py @@ -27,9 +27,9 @@ import unittest from functools import wraps from inspect import iscoroutinefunction +from typing import TYPE_CHECKING from bson.son import SON -from pymongo import MongoClient from pymongo.errors import ConfigurationError from pymongo.hello import HelloCompat from pymongo.lock import _create_lock @@ -37,7 +37,10 @@ from pymongo.pool_shared import _CancellationContext, _PoolGeneration from pymongo.read_preferences import ReadPreference from pymongo.server_selectors import any_server_selector, writable_server_selector -from pymongo.synchronous.pool import Pool + +if TYPE_CHECKING: + from pymongo import MongoClient + from pymongo.synchronous.pool import Pool _IS_SYNC = True