Skip to content

Commit c8b8395

Browse files
authored
Merge branch 'master' into PYTHON-4636
2 parents 0e03581 + 821811e commit c8b8395

37 files changed

+1293
-223
lines changed

.evergreen/run-tests.sh

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,9 @@ if [ -n "$PERF_TEST" ]; then
224224
python -m pip install simplejson
225225
start_time=$(date +%s)
226226
TEST_SUITES="perf"
227+
# PYTHON-4769 Run perf_test.py directly otherwise pytest's test collection negatively
228+
# affects the benchmark results.
229+
TEST_ARGS="test/performance/perf_test.py $TEST_ARGS"
227230
fi
228231

229232
echo "Running $AUTH tests over $SSL with python $(which python)"

bson/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,7 +1324,7 @@ def decode_iter(
13241324
elements = data[position : position + obj_size]
13251325
position += obj_size
13261326

1327-
yield _bson_to_dict(elements, opts) # type:ignore[misc, type-var]
1327+
yield _bson_to_dict(elements, opts) # type:ignore[misc]
13281328

13291329

13301330
@overload
@@ -1370,7 +1370,7 @@ def decode_file_iter(
13701370
raise InvalidBSON("cut off in middle of objsize")
13711371
obj_size = _UNPACK_INT_FROM(size_data, 0)[0] - 4
13721372
elements = size_data + file_obj.read(max(0, obj_size))
1373-
yield _bson_to_dict(elements, opts) # type:ignore[type-var, arg-type, misc]
1373+
yield _bson_to_dict(elements, opts) # type:ignore[arg-type, misc]
13741374

13751375

13761376
def is_valid(bson: bytes) -> bool:

bson/decimal128.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ def __init__(self, value: _VALUE_OPTIONS) -> None:
223223
"from list or tuple. Must have exactly 2 "
224224
"elements."
225225
)
226-
self.__high, self.__low = value # type: ignore
226+
self.__high, self.__low = value
227227
else:
228228
raise TypeError(f"Cannot convert {value!r} to Decimal128")
229229

bson/json_util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ def __new__(
324324
"JSONOptions.datetime_representation must be one of LEGACY, "
325325
"NUMBERLONG, or ISO8601 from DatetimeRepresentation."
326326
)
327-
self = cast(JSONOptions, super().__new__(cls, *args, **kwargs)) # type:ignore[arg-type]
327+
self = cast(JSONOptions, super().__new__(cls, *args, **kwargs))
328328
if json_mode not in (JSONMode.LEGACY, JSONMode.RELAXED, JSONMode.CANONICAL):
329329
raise ValueError(
330330
"JSONOptions.json_mode must be one of LEGACY, RELAXED, "

bson/son.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def __init__(
6868
self.update(kwargs)
6969

7070
def __new__(cls: Type[SON[_Key, _Value]], *args: Any, **kwargs: Any) -> SON[_Key, _Value]:
71-
instance = super().__new__(cls, *args, **kwargs) # type: ignore[type-var]
71+
instance = super().__new__(cls, *args, **kwargs)
7272
instance.__keys = []
7373
return instance
7474

hatch.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@ features = ["docs","test"]
1313
test = "sphinx-build -E -b doctest doc ./doc/_build/doctest"
1414

1515
[envs.typing]
16-
features = ["encryption", "ocsp", "zstd", "aws"]
17-
dependencies = ["mypy==1.2.0","pyright==1.1.290", "certifi", "typing_extensions"]
16+
pre-install-commands = [
17+
"pip install -q -r requirements/typing.txt",
18+
]
1819
[envs.typing.scripts]
1920
check-mypy = [
2021
"mypy --install-types --non-interactive bson gridfs tools pymongo",

pymongo/__init__.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,7 @@
8888

8989
from pymongo import _csot
9090
from pymongo._version import __version__, get_version_string, version_tuple
91-
from pymongo.asynchronous.mongo_client import AsyncMongoClient
92-
from pymongo.common import MAX_SUPPORTED_WIRE_VERSION, MIN_SUPPORTED_WIRE_VERSION
91+
from pymongo.common import MAX_SUPPORTED_WIRE_VERSION, MIN_SUPPORTED_WIRE_VERSION, has_c
9392
from pymongo.cursor import CursorType
9493
from pymongo.operations import (
9594
DeleteMany,
@@ -105,18 +104,16 @@
105104
from pymongo.synchronous.mongo_client import MongoClient
106105
from pymongo.write_concern import WriteConcern
107106

108-
version = __version__
109-
"""Current version of PyMongo."""
110-
107+
try:
108+
from pymongo.asynchronous.mongo_client import AsyncMongoClient
109+
except Exception as e:
110+
# PYTHON-4781: Importing asyncio can fail on Windows.
111+
import warnings as _warnings
111112

112-
def has_c() -> bool:
113-
"""Is the C extension installed?"""
114-
try:
115-
from pymongo import _cmessage # type: ignore[attr-defined] # noqa: F401
113+
_warnings.warn(f"Failed to import Async PyMongo: {e!r}", ImportWarning, stacklevel=2)
116114

117-
return True
118-
except ImportError:
119-
return False
115+
version = __version__
116+
"""Current version of PyMongo."""
120117

121118

122119
def timeout(seconds: Optional[float]) -> ContextManager[None]:

pymongo/_csot.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,13 @@ def __init__(self, timeout: Optional[float]):
7575
self._timeout = timeout
7676
self._tokens: Optional[tuple[Token[Optional[float]], Token[float], Token[float]]] = None
7777

78-
def __enter__(self) -> _TimeoutContext:
78+
def __enter__(self) -> None:
7979
timeout_token = TIMEOUT.set(self._timeout)
8080
prev_deadline = DEADLINE.get()
8181
next_deadline = time.monotonic() + self._timeout if self._timeout else float("inf")
8282
deadline_token = DEADLINE.set(min(prev_deadline, next_deadline))
8383
rtt_token = RTT.set(0.0)
8484
self._tokens = (timeout_token, deadline_token, rtt_token)
85-
return self
8685

8786
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
8887
if self._tokens:

pymongo/asynchronous/collection.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
TypeVar,
3636
Union,
3737
cast,
38+
overload,
3839
)
3940

4041
from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions
@@ -332,13 +333,33 @@ def database(self) -> AsyncDatabase[_DocumentType]:
332333
"""
333334
return self._database
334335

336+
@overload
337+
def with_options(
338+
self,
339+
codec_options: None = None,
340+
read_preference: Optional[_ServerMode] = ...,
341+
write_concern: Optional[WriteConcern] = ...,
342+
read_concern: Optional[ReadConcern] = ...,
343+
) -> AsyncCollection[_DocumentType]:
344+
...
345+
346+
@overload
347+
def with_options(
348+
self,
349+
codec_options: bson.CodecOptions[_DocumentTypeArg],
350+
read_preference: Optional[_ServerMode] = ...,
351+
write_concern: Optional[WriteConcern] = ...,
352+
read_concern: Optional[ReadConcern] = ...,
353+
) -> AsyncCollection[_DocumentTypeArg]:
354+
...
355+
335356
def with_options(
336357
self,
337358
codec_options: Optional[bson.CodecOptions[_DocumentTypeArg]] = None,
338359
read_preference: Optional[_ServerMode] = None,
339360
write_concern: Optional[WriteConcern] = None,
340361
read_concern: Optional[ReadConcern] = None,
341-
) -> AsyncCollection[_DocumentType]:
362+
) -> AsyncCollection[_DocumentType] | AsyncCollection[_DocumentTypeArg]:
342363
"""Get a clone of this collection changing the specified settings.
343364
344365
>>> coll1.read_preference

pymongo/asynchronous/database.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,13 +146,33 @@ def name(self) -> str:
146146
"""The name of this :class:`AsyncDatabase`."""
147147
return self._name
148148

149+
@overload
150+
def with_options(
151+
self,
152+
codec_options: None = None,
153+
read_preference: Optional[_ServerMode] = ...,
154+
write_concern: Optional[WriteConcern] = ...,
155+
read_concern: Optional[ReadConcern] = ...,
156+
) -> AsyncDatabase[_DocumentType]:
157+
...
158+
159+
@overload
160+
def with_options(
161+
self,
162+
codec_options: bson.CodecOptions[_DocumentTypeArg],
163+
read_preference: Optional[_ServerMode] = ...,
164+
write_concern: Optional[WriteConcern] = ...,
165+
read_concern: Optional[ReadConcern] = ...,
166+
) -> AsyncDatabase[_DocumentTypeArg]:
167+
...
168+
149169
def with_options(
150170
self,
151171
codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None,
152172
read_preference: Optional[_ServerMode] = None,
153173
write_concern: Optional[WriteConcern] = None,
154174
read_concern: Optional[ReadConcern] = None,
155-
) -> AsyncDatabase[_DocumentType]:
175+
) -> AsyncDatabase[_DocumentType] | AsyncDatabase[_DocumentTypeArg]:
156176
"""Get a clone of this database changing the specified settings.
157177
158178
>>> db1.read_preference

pymongo/asynchronous/pool.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -913,7 +913,7 @@ async def _configured_socket(
913913
and not options.tls_allow_invalid_hostnames
914914
):
915915
try:
916-
ssl.match_hostname(ssl_sock.getpeercert(), hostname=host)
916+
ssl.match_hostname(ssl_sock.getpeercert(), hostname=host) # type:ignore[attr-defined]
917917
except _CertificateError:
918918
ssl_sock.close()
919919
raise
@@ -992,7 +992,8 @@ def __init__(
992992
# from the right side.
993993
self.conns: collections.deque = collections.deque()
994994
self.active_contexts: set[_CancellationContext] = set()
995-
self.lock = _ALock(_create_lock())
995+
_lock = _create_lock()
996+
self.lock = _ALock(_lock)
996997
self.active_sockets = 0
997998
# Monotonically increasing connection ID required for CMAP Events.
998999
self.next_connection_id = 1
@@ -1018,15 +1019,15 @@ def __init__(
10181019
# The first portion of the wait queue.
10191020
# Enforces: maxPoolSize
10201021
# Also used for: clearing the wait queue
1021-
self.size_cond = _ACondition(threading.Condition(self.lock)) # type: ignore[arg-type]
1022+
self.size_cond = _ACondition(threading.Condition(_lock))
10221023
self.requests = 0
10231024
self.max_pool_size = self.opts.max_pool_size
10241025
if not self.max_pool_size:
10251026
self.max_pool_size = float("inf")
10261027
# The second portion of the wait queue.
10271028
# Enforces: maxConnecting
10281029
# Also used for: clearing the wait queue
1029-
self._max_connecting_cond = _ACondition(threading.Condition(self.lock)) # type: ignore[arg-type]
1030+
self._max_connecting_cond = _ACondition(threading.Condition(_lock))
10301031
self._max_connecting = self.opts.max_connecting
10311032
self._pending = 0
10321033
self._client_id = client_id

pymongo/asynchronous/topology.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,9 @@ def __init__(self, topology_settings: TopologySettings):
170170
self._seed_addresses = list(topology_description.server_descriptions())
171171
self._opened = False
172172
self._closed = False
173-
self._lock = _ALock(_create_lock())
174-
self._condition = _ACondition(self._settings.condition_class(self._lock)) # type: ignore[arg-type]
173+
_lock = _create_lock()
174+
self._lock = _ALock(_lock)
175+
self._condition = _ACondition(self._settings.condition_class(_lock))
175176
self._servers: dict[_Address, Server] = {}
176177
self._pid: Optional[int] = None
177178
self._max_cluster_time: Optional[ClusterTime] = None

pymongo/common.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -850,7 +850,7 @@ def get_normed_key(x: str) -> str:
850850
return x
851851

852852
def get_setter_key(x: str) -> str:
853-
return options.cased_key(x) # type: ignore[attr-defined]
853+
return options.cased_key(x)
854854

855855
else:
856856
validated_options = {}
@@ -1060,3 +1060,13 @@ def update(self, other: Mapping[str, Any]) -> None: # type: ignore[override]
10601060

10611061
def cased_key(self, key: str) -> Any:
10621062
return self.__casedkeys[key.lower()]
1063+
1064+
1065+
def has_c() -> bool:
1066+
"""Is the C extension installed?"""
1067+
try:
1068+
from pymongo import _cmessage # type: ignore[attr-defined] # noqa: F401
1069+
1070+
return True
1071+
except ImportError:
1072+
return False

pymongo/compression_support.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
def _have_snappy() -> bool:
2828
try:
29-
import snappy # type:ignore[import] # noqa: F401
29+
import snappy # type:ignore[import-not-found] # noqa: F401
3030

3131
return True
3232
except ImportError:

pymongo/encryption_options.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from typing import TYPE_CHECKING, Any, Mapping, Optional
2222

2323
try:
24-
import pymongocrypt # type:ignore[import] # noqa: F401
24+
import pymongocrypt # type:ignore[import-untyped] # noqa: F401
2525

2626
# Check for pymongocrypt>=1.10.
2727
from pymongocrypt import synchronous as _ # noqa: F401

0 commit comments

Comments
 (0)