Skip to content

Commit c1d3383

Browse files
authored
PYTHON-3907 add --disallow-untyped-defs for mypy (#1351)
1 parent f7738b8 commit c1d3383

25 files changed

+43
-36
lines changed

bson/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1406,7 +1406,7 @@ def has_c() -> bool:
14061406
return _USE_C
14071407

14081408

1409-
def _after_fork():
1409+
def _after_fork() -> None:
14101410
"""Releases the ObjectID lock child."""
14111411
if ObjectId._inc_lock.locked():
14121412
ObjectId._inc_lock.release()

bson/binary.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -365,5 +365,5 @@ def __hash__(self) -> int:
365365
def __ne__(self, other: Any) -> bool:
366366
return not self == other
367367

368-
def __repr__(self):
368+
def __repr__(self) -> str:
369369
return f"Binary({bytes.__repr__(self)}, {self.__subtype})"

bson/code.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def scope(self) -> Optional[Mapping[str, Any]]:
8686
"""Scope dictionary for this instance or ``None``."""
8787
return self.__scope
8888

89-
def __repr__(self):
89+
def __repr__(self) -> str:
9090
return f"Code({str.__repr__(self)}, {self.__scope!r})"
9191

9292
def __eq__(self, other: Any) -> bool:

bson/codec_options.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
172172
)
173173
raise TypeError(err_msg)
174174

175-
def __repr__(self):
175+
def __repr__(self) -> str:
176176
return "{}(type_codecs={!r}, fallback_encoder={!r})".format(
177177
self.__class__.__name__,
178178
self.__type_codecs,
@@ -465,7 +465,7 @@ def _options_dict(self) -> Dict[str, Any]:
465465
"datetime_conversion": self.datetime_conversion,
466466
}
467467

468-
def __repr__(self):
468+
def __repr__(self) -> str:
469469
return f"{self.__class__.__name__}({self._arguments_repr()})"
470470

471471
def with_options(self, **kwargs: Any) -> "CodecOptions":

bson/datetime_ms.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -111,12 +111,12 @@ def __int__(self) -> int:
111111
# Timezones are hashed by their offset, which is a timedelta
112112
# and therefore there are more than 24 possible timezones.
113113
@functools.lru_cache(maxsize=None)
114-
def _min_datetime_ms(tz=datetime.timezone.utc):
114+
def _min_datetime_ms(tz: datetime.timezone = datetime.timezone.utc) -> int:
115115
return _datetime_to_millis(datetime.datetime.min.replace(tzinfo=tz))
116116

117117

118118
@functools.lru_cache(maxsize=None)
119-
def _max_datetime_ms(tz=datetime.timezone.utc):
119+
def _max_datetime_ms(tz: datetime.timezone = datetime.timezone.utc) -> int:
120120
return _datetime_to_millis(datetime.datetime.max.replace(tzinfo=tz))
121121

122122

bson/dbref.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def as_doc(self) -> SON[str, Any]:
101101
doc.update(self.__kwargs)
102102
return doc
103103

104-
def __repr__(self):
104+
def __repr__(self) -> str:
105105
extra = "".join([f", {k}={v!r}" for k, v in self.__kwargs.items()])
106106
if self.database is None:
107107
return f"DBRef({self.collection!r}, {self.id!r}{extra})"

bson/decimal128.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def __str__(self) -> str:
296296
return "NaN"
297297
return str(dec)
298298

299-
def __repr__(self):
299+
def __repr__(self) -> str:
300300
return f"Decimal128('{str(self)}')"
301301

302302
def __setstate__(self, value: Tuple[int, int]) -> None:

bson/json_util.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ class JSONOptions(CodecOptions):
224224
datetime_representation: int
225225
strict_uuid: bool
226226

227-
def __init__(self, *args, **kwargs):
227+
def __init__(self, *args: Any, **kwargs: Any):
228228
"""Encapsulates JSON options for :func:`dumps` and :func:`loads`.
229229
230230
:Parameters:

bson/max_key.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,5 @@ def __ge__(self, dummy: Any) -> bool:
5050
def __gt__(self, other: Any) -> bool:
5151
return not isinstance(other, MaxKey)
5252

53-
def __repr__(self):
53+
def __repr__(self) -> str:
5454
return "MaxKey()"

bson/min_key.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,5 @@ def __ge__(self, other: Any) -> bool:
5050
def __gt__(self, dummy: Any) -> bool:
5151
return False
5252

53-
def __repr__(self):
53+
def __repr__(self) -> str:
5454
return "MinKey()"

bson/objectid.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def __setstate__(self, value: Any) -> None:
243243
def __str__(self) -> str:
244244
return binascii.hexlify(self.__id).decode()
245245

246-
def __repr__(self):
246+
def __repr__(self) -> str:
247247
return f"ObjectId('{str(self)}')"
248248

249249
def __eq__(self, other: Any) -> bool:

bson/raw_bson.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def __eq__(self, other: Any) -> bool:
173173
return self.__raw == other.raw
174174
return NotImplemented
175175

176-
def __repr__(self):
176+
def __repr__(self) -> str:
177177
return "{}({!r}, codec_options={!r})".format(
178178
self.__class__.__name__,
179179
self.raw,

bson/regex.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def __eq__(self, other: Any) -> bool:
115115
def __ne__(self, other: Any) -> bool:
116116
return not self == other
117117

118-
def __repr__(self):
118+
def __repr__(self) -> str:
119119
return f"Regex({self.pattern!r}, {self.flags!r})"
120120

121121
def try_compile(self) -> "Pattern[_T]":

bson/son.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def __new__(cls: Type["SON[_Key, _Value]"], *args: Any, **kwargs: Any) -> "SON[_
7171
instance.__keys = []
7272
return instance
7373

74-
def __repr__(self):
74+
def __repr__(self) -> str:
7575
result = []
7676
for key in self.__keys:
7777
result.append(f"({key!r}, {self[key]!r})")

bson/timestamp.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def __ge__(self, other: Any) -> bool:
111111
return (self.time, self.inc) >= (other.time, other.inc)
112112
return NotImplemented
113113

114-
def __repr__(self):
114+
def __repr__(self) -> str:
115115
return f"Timestamp({self.__time}, {self.__inc})"
116116

117117
def as_datetime(self) -> datetime.datetime:

pymongo/_csot.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
"""Internal helpers for CSOT."""
1616

17+
from __future__ import annotations
18+
1719
import functools
1820
import time
1921
from collections import deque
@@ -72,7 +74,7 @@ def __init__(self, timeout: Optional[float]):
7274
self._timeout = timeout
7375
self._tokens: Optional[Tuple[Token, Token, Token]] = None
7476

75-
def __enter__(self):
77+
def __enter__(self) -> _TimeoutContext:
7678
timeout_token = TIMEOUT.set(self._timeout)
7779
prev_deadline = DEADLINE.get()
7880
next_deadline = time.monotonic() + self._timeout if self._timeout else float("inf")
@@ -81,7 +83,7 @@ def __enter__(self):
8183
self._tokens = (timeout_token, deadline_token, rtt_token)
8284
return self
8385

84-
def __exit__(self, exc_type, exc_val, exc_tb):
86+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
8587
if self._tokens:
8688
timeout_token, deadline_token, rtt_token = self._tokens
8789
TIMEOUT.reset(timeout_token)
@@ -97,7 +99,7 @@ def apply(func: F) -> F:
9799
"""Apply the client's timeoutMS to this operation."""
98100

99101
@functools.wraps(func)
100-
def csot_wrapper(self, *args, **kwargs):
102+
def csot_wrapper(self: Any, *args: Any, **kwargs: Any) -> F:
101103
if get_timeout() is None:
102104
timeout = self._timeout
103105
if timeout is not None:

pymongo/auth_aws.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
except ImportError:
2424

2525
class AwsSaslContext: # type: ignore
26-
def __init__(self, credentials):
26+
def __init__(self, credentials: MongoCredential):
2727
pass
2828

2929
_HAVE_MONGODB_AWS = False
@@ -35,11 +35,11 @@ def __init__(self, credentials):
3535
set_use_cached_credentials(True)
3636
except ImportError:
3737

38-
def set_cached_credentials(creds):
38+
def set_cached_credentials(creds: Optional[AwsCredential]) -> None:
3939
pass
4040

4141

42-
from typing import TYPE_CHECKING, Any, Mapping
42+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Type
4343

4444
import bson
4545
from bson.binary import Binary
@@ -54,7 +54,7 @@ def set_cached_credentials(creds):
5454

5555
class _AwsSaslContext(AwsSaslContext): # type: ignore
5656
# Dependency injection:
57-
def binary_type(self):
57+
def binary_type(self) -> Type[Binary]:
5858
"""Return the bson.binary.Binary type."""
5959
return Binary
6060

pymongo/change_stream.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ def _run_aggregation_cmd(
257257
cmd.get_cursor, self._target._read_preference_for(session), session
258258
)
259259

260-
def _create_cursor(self):
260+
def _create_cursor(self) -> CommandCursor:
261261
with self._client._tmp_session(self._session, close=False) as s:
262262
return self._run_aggregation_cmd(session=s, explicit_session=self._session is not None)
263263

pymongo/collation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def document(self) -> Dict[str, Any]:
199199
"""
200200
return self.__document.copy()
201201

202-
def __repr__(self):
202+
def __repr__(self) -> str:
203203
document = self.document
204204
return "Collation({})".format(", ".join(f"{key}={document[key]!r}" for key in document))
205205

pymongo/collection.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2481,7 +2481,7 @@ def create_search_indexes(
24812481
if comment is not None:
24822482
kwargs["comment"] = comment
24832483

2484-
def gen_indexes():
2484+
def gen_indexes() -> Iterator[Mapping[str, Any]]:
24852485
for index in models:
24862486
if not isinstance(index, SearchIndexModel):
24872487
raise TypeError(

pymongo/event_loggers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ class ConnectionPoolLogger(monitoring.ConnectionPoolListener):
179179
def pool_created(self, event: monitoring.PoolCreatedEvent) -> None:
180180
logging.info(f"[pool {event.address}] pool created")
181181

182-
def pool_ready(self, event):
182+
def pool_ready(self, event: monitoring.PoolReadyEvent) -> None:
183183
logging.info(f"[pool {event.address}] pool ready")
184184

185185
def pool_cleared(self, event: monitoring.PoolClearedEvent) -> None:

pymongo/ocsp_cache.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from collections import namedtuple
2020
from datetime import datetime as _datetime
2121
from datetime import timezone
22-
from typing import TYPE_CHECKING
22+
from typing import TYPE_CHECKING, Any, Dict
2323

2424
from pymongo.lock import _create_lock
2525

@@ -35,8 +35,8 @@ class _OCSPCache:
3535
["hash_algorithm", "issuer_name_hash", "issuer_key_hash", "serial_number"],
3636
)
3737

38-
def __init__(self):
39-
self._data = {}
38+
def __init__(self) -> None:
39+
self._data: Dict[Any, OCSPResponse] = {}
4040
# Hold this lock when accessing _data.
4141
self._lock = _create_lock()
4242

@@ -77,7 +77,10 @@ def __setitem__(self, key: OCSPRequest, value: OCSPResponse) -> None:
7777
# Cache new response OR update cached response if new response
7878
# has longer validity.
7979
cached_value = self._data.get(cache_key, None)
80-
if cached_value is None or cached_value.next_update < value.next_update:
80+
if cached_value is None or (
81+
cached_value.next_update is not None
82+
and cached_value.next_update < value.next_update
83+
):
8184
self._data[cache_key] = value
8285

8386
def __getitem__(self, item: OCSPRequest) -> OCSPResponse:
@@ -92,6 +95,8 @@ def __getitem__(self, item: OCSPRequest) -> OCSPResponse:
9295
value = self._data[cache_key]
9396

9497
# Return cached response if it is still valid.
98+
assert value.this_update is not None
99+
assert value.next_update is not None
95100
if (
96101
value.this_update
97102
<= _datetime.now(tz=timezone.utc).replace(tzinfo=None)

pymongo/topology.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -890,7 +890,7 @@ def __repr__(self) -> str:
890890
msg = "CLOSED "
891891
return f"<{self.__class__.__name__} {msg}{self._description!r}>"
892892

893-
def eq_props(self):
893+
def eq_props(self) -> Tuple[Tuple[_Address, ...], Optional[str], Optional[str], str]:
894894
"""The properties to use for MongoClient/Topology equality checks."""
895895
ts = self._settings
896896
return (tuple(sorted(ts.seeds)), ts.replica_set_name, ts.fqdn, ts.srv_service_name)

tools/ocsptest.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
2626

2727

28-
def check_ocsp(host, port, capath):
28+
def check_ocsp(host: str, port: int, capath: str) -> None:
2929
ctx = get_ssl_context(
3030
None, # certfile
3131
None, # passphrase
@@ -47,7 +47,7 @@ def check_ocsp(host, port, capath):
4747
s.close()
4848

4949

50-
def main():
50+
def main() -> None:
5151
parser = argparse.ArgumentParser(description="Debug OCSP")
5252
parser.add_argument("--host", type=str, required=True, help="Host to connect to")
5353
parser.add_argument("-p", "--port", type=int, default=443, help="Port to connect to")

tox.ini

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ deps =
8686
certifi; platform_system == "win32" or platform_system == "Darwin"
8787
typing_extensions
8888
commands =
89-
mypy --install-types --non-interactive bson gridfs tools pymongo
89+
mypy --install-types --non-interactive --disallow-untyped-defs bson gridfs tools pymongo
9090
mypy --install-types --non-interactive --disable-error-code var-annotated --disable-error-code attr-defined --disable-error-code union-attr --disable-error-code assignment --disable-error-code no-redef --disable-error-code index --allow-redefinition --allow-untyped-globals --exclude "test/mypy_fails/*.*" --exclude "test/conftest.py" test
9191
mypy --install-types --non-interactive test/test_typing.py test/test_typing_strict.py
9292

0 commit comments

Comments
 (0)