Skip to content

Commit bbb6f88

Browse files
authored
PYTHON-5257 - Turn on mypy disallow_any_generics (#2456)
1 parent d7074ba commit bbb6f88

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+323
-297
lines changed

bson/json_util.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ def _encode_binary(data: bytes, subtype: int, json_options: JSONOptions) -> Any:
844844
return {"$binary": {"base64": base64.b64encode(data).decode(), "subType": "%02x" % subtype}}
845845

846846

847-
def _encode_datetimems(obj: Any, json_options: JSONOptions) -> dict:
847+
def _encode_datetimems(obj: Any, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
848848
if (
849849
json_options.datetime_representation == DatetimeRepresentation.ISO8601
850850
and 0 <= int(obj) <= _MAX_UTC_MS
@@ -855,7 +855,7 @@ def _encode_datetimems(obj: Any, json_options: JSONOptions) -> dict:
855855
return {"$date": {"$numberLong": str(int(obj))}}
856856

857857

858-
def _encode_code(obj: Code, json_options: JSONOptions) -> dict:
858+
def _encode_code(obj: Code, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
859859
if obj.scope is None:
860860
return {"$code": str(obj)}
861861
else:
@@ -873,7 +873,7 @@ def _encode_noop(obj: Any, dummy0: Any) -> Any:
873873
return obj
874874

875875

876-
def _encode_regex(obj: Any, json_options: JSONOptions) -> dict:
876+
def _encode_regex(obj: Any, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
877877
flags = ""
878878
if obj.flags & re.IGNORECASE:
879879
flags += "i"
@@ -918,7 +918,7 @@ def _encode_float(obj: float, json_options: JSONOptions) -> Any:
918918
return obj
919919

920920

921-
def _encode_datetime(obj: datetime.datetime, json_options: JSONOptions) -> dict:
921+
def _encode_datetime(obj: datetime.datetime, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
922922
if json_options.datetime_representation == DatetimeRepresentation.ISO8601:
923923
if not obj.tzinfo:
924924
obj = obj.replace(tzinfo=utc)
@@ -941,51 +941,51 @@ def _encode_datetime(obj: datetime.datetime, json_options: JSONOptions) -> dict:
941941
return {"$date": {"$numberLong": str(millis)}}
942942

943943

944-
def _encode_bytes(obj: bytes, json_options: JSONOptions) -> dict:
944+
def _encode_bytes(obj: bytes, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
945945
return _encode_binary(obj, 0, json_options)
946946

947947

948-
def _encode_binary_obj(obj: Binary, json_options: JSONOptions) -> dict:
948+
def _encode_binary_obj(obj: Binary, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
949949
return _encode_binary(obj, obj.subtype, json_options)
950950

951951

952-
def _encode_uuid(obj: uuid.UUID, json_options: JSONOptions) -> dict:
952+
def _encode_uuid(obj: uuid.UUID, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
953953
if json_options.strict_uuid:
954954
binval = Binary.from_uuid(obj, uuid_representation=json_options.uuid_representation)
955955
return _encode_binary(binval, binval.subtype, json_options)
956956
else:
957957
return {"$uuid": obj.hex}
958958

959959

960-
def _encode_objectid(obj: ObjectId, dummy0: Any) -> dict:
960+
def _encode_objectid(obj: ObjectId, dummy0: Any) -> dict: # type: ignore[type-arg]
961961
return {"$oid": str(obj)}
962962

963963

964-
def _encode_timestamp(obj: Timestamp, dummy0: Any) -> dict:
964+
def _encode_timestamp(obj: Timestamp, dummy0: Any) -> dict: # type: ignore[type-arg]
965965
return {"$timestamp": {"t": obj.time, "i": obj.inc}}
966966

967967

968-
def _encode_decimal128(obj: Timestamp, dummy0: Any) -> dict:
968+
def _encode_decimal128(obj: Timestamp, dummy0: Any) -> dict: # type: ignore[type-arg]
969969
return {"$numberDecimal": str(obj)}
970970

971971

972-
def _encode_dbref(obj: DBRef, json_options: JSONOptions) -> dict:
972+
def _encode_dbref(obj: DBRef, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
973973
return _json_convert(obj.as_doc(), json_options=json_options)
974974

975975

976-
def _encode_minkey(dummy0: Any, dummy1: Any) -> dict:
976+
def _encode_minkey(dummy0: Any, dummy1: Any) -> dict: # type: ignore[type-arg]
977977
return {"$minKey": 1}
978978

979979

980-
def _encode_maxkey(dummy0: Any, dummy1: Any) -> dict:
980+
def _encode_maxkey(dummy0: Any, dummy1: Any) -> dict: # type: ignore[type-arg]
981981
return {"$maxKey": 1}
982982

983983

984984
# Encoders for BSON types
985985
# Each encoder function's signature is:
986986
# - obj: a Python data type, e.g. a Python int for _encode_int
987987
# - json_options: a JSONOptions
988-
_ENCODERS: dict[Type, Callable[[Any, JSONOptions], Any]] = {
988+
_ENCODERS: dict[Type, Callable[[Any, JSONOptions], Any]] = { # type: ignore[type-arg]
989989
bool: _encode_noop,
990990
bytes: _encode_bytes,
991991
datetime.datetime: _encode_datetime,
@@ -1056,7 +1056,7 @@ def _get_datetime_size(obj: datetime.datetime) -> int:
10561056
return 5 + len(str(obj.time()))
10571057

10581058

1059-
def _get_regex_size(obj: Regex) -> int:
1059+
def _get_regex_size(obj: Regex) -> int: # type: ignore[type-arg]
10601060
return 18 + len(obj.pattern)
10611061

10621062

bson/typings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,4 @@
2828
_DocumentOut = Union[MutableMapping[str, Any], "RawBSONDocument"]
2929
_DocumentType = TypeVar("_DocumentType", bound=Mapping[str, Any])
3030
_DocumentTypeArg = TypeVar("_DocumentTypeArg", bound=Mapping[str, Any])
31-
_ReadableBuffer = Union[bytes, memoryview, "mmap", "array"]
31+
_ReadableBuffer = Union[bytes, memoryview, "mmap", "array"] # type: ignore[type-arg]

gridfs/asynchronous/grid_file.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def _disallow_transactions(session: Optional[AsyncClientSession]) -> None:
7070
class AsyncGridFS:
7171
"""An instance of GridFS on top of a single Database."""
7272

73-
def __init__(self, database: AsyncDatabase, collection: str = "fs"):
73+
def __init__(self, database: AsyncDatabase[Any], collection: str = "fs"):
7474
"""Create a new instance of :class:`GridFS`.
7575
7676
Raises :class:`TypeError` if `database` is not an instance of
@@ -463,7 +463,7 @@ class AsyncGridFSBucket:
463463

464464
def __init__(
465465
self,
466-
db: AsyncDatabase,
466+
db: AsyncDatabase[Any],
467467
bucket_name: str = "fs",
468468
chunk_size_bytes: int = DEFAULT_CHUNK_SIZE,
469469
write_concern: Optional[WriteConcern] = None,
@@ -513,11 +513,11 @@ def __init__(
513513

514514
self._bucket_name = bucket_name
515515
self._collection = db[bucket_name]
516-
self._chunks: AsyncCollection = self._collection.chunks.with_options(
516+
self._chunks: AsyncCollection[Any] = self._collection.chunks.with_options(
517517
write_concern=write_concern, read_preference=read_preference
518518
)
519519

520-
self._files: AsyncCollection = self._collection.files.with_options(
520+
self._files: AsyncCollection[Any] = self._collection.files.with_options(
521521
write_concern=write_concern, read_preference=read_preference
522522
)
523523

@@ -1085,7 +1085,7 @@ class AsyncGridIn:
10851085

10861086
def __init__(
10871087
self,
1088-
root_collection: AsyncCollection,
1088+
root_collection: AsyncCollection[Any],
10891089
session: Optional[AsyncClientSession] = None,
10901090
**kwargs: Any,
10911091
) -> None:
@@ -1172,7 +1172,7 @@ def __init__(
11721172
object.__setattr__(self, "_buffered_docs_size", 0)
11731173

11741174
async def _create_index(
1175-
self, collection: AsyncCollection, index_key: Any, unique: bool
1175+
self, collection: AsyncCollection[Any], index_key: Any, unique: bool
11761176
) -> None:
11771177
doc = await collection.find_one(projection={"_id": 1}, session=self._session)
11781178
if doc is None:
@@ -1456,7 +1456,7 @@ class AsyncGridOut(GRIDOUT_BASE_CLASS): # type: ignore
14561456

14571457
def __init__(
14581458
self,
1459-
root_collection: AsyncCollection,
1459+
root_collection: AsyncCollection[Any],
14601460
file_id: Optional[int] = None,
14611461
file_document: Optional[Any] = None,
14621462
session: Optional[AsyncClientSession] = None,
@@ -1829,7 +1829,7 @@ class _AsyncGridOutChunkIterator:
18291829
def __init__(
18301830
self,
18311831
grid_out: AsyncGridOut,
1832-
chunks: AsyncCollection,
1832+
chunks: AsyncCollection[Any],
18331833
session: Optional[AsyncClientSession],
18341834
next_chunk: Any,
18351835
) -> None:
@@ -1842,7 +1842,7 @@ def __init__(
18421842
self._num_chunks = math.ceil(float(self._length) / self._chunk_size)
18431843
self._cursor = None
18441844

1845-
_cursor: Optional[AsyncCursor]
1845+
_cursor: Optional[AsyncCursor[Any]]
18461846

18471847
def expected_chunk_length(self, chunk_n: int) -> int:
18481848
if chunk_n < self._num_chunks - 1:
@@ -1921,7 +1921,7 @@ async def close(self) -> None:
19211921

19221922
class AsyncGridOutIterator:
19231923
def __init__(
1924-
self, grid_out: AsyncGridOut, chunks: AsyncCollection, session: AsyncClientSession
1924+
self, grid_out: AsyncGridOut, chunks: AsyncCollection[Any], session: AsyncClientSession
19251925
):
19261926
self._chunk_iter = _AsyncGridOutChunkIterator(grid_out, chunks, session, 0)
19271927

@@ -1935,14 +1935,14 @@ async def next(self) -> bytes:
19351935
__anext__ = next
19361936

19371937

1938-
class AsyncGridOutCursor(AsyncCursor):
1938+
class AsyncGridOutCursor(AsyncCursor): # type: ignore[type-arg]
19391939
"""A cursor / iterator for returning GridOut objects as the result
19401940
of an arbitrary query against the GridFS files collection.
19411941
"""
19421942

19431943
def __init__(
19441944
self,
1945-
collection: AsyncCollection,
1945+
collection: AsyncCollection[Any],
19461946
filter: Optional[Mapping[str, Any]] = None,
19471947
skip: int = 0,
19481948
limit: int = 0,

gridfs/synchronous/grid_file.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def _disallow_transactions(session: Optional[ClientSession]) -> None:
7070
class GridFS:
7171
"""An instance of GridFS on top of a single Database."""
7272

73-
def __init__(self, database: Database, collection: str = "fs"):
73+
def __init__(self, database: Database[Any], collection: str = "fs"):
7474
"""Create a new instance of :class:`GridFS`.
7575
7676
Raises :class:`TypeError` if `database` is not an instance of
@@ -461,7 +461,7 @@ class GridFSBucket:
461461

462462
def __init__(
463463
self,
464-
db: Database,
464+
db: Database[Any],
465465
bucket_name: str = "fs",
466466
chunk_size_bytes: int = DEFAULT_CHUNK_SIZE,
467467
write_concern: Optional[WriteConcern] = None,
@@ -511,11 +511,11 @@ def __init__(
511511

512512
self._bucket_name = bucket_name
513513
self._collection = db[bucket_name]
514-
self._chunks: Collection = self._collection.chunks.with_options(
514+
self._chunks: Collection[Any] = self._collection.chunks.with_options(
515515
write_concern=write_concern, read_preference=read_preference
516516
)
517517

518-
self._files: Collection = self._collection.files.with_options(
518+
self._files: Collection[Any] = self._collection.files.with_options(
519519
write_concern=write_concern, read_preference=read_preference
520520
)
521521

@@ -1077,7 +1077,7 @@ class GridIn:
10771077

10781078
def __init__(
10791079
self,
1080-
root_collection: Collection,
1080+
root_collection: Collection[Any],
10811081
session: Optional[ClientSession] = None,
10821082
**kwargs: Any,
10831083
) -> None:
@@ -1163,7 +1163,7 @@ def __init__(
11631163
object.__setattr__(self, "_buffered_docs", [])
11641164
object.__setattr__(self, "_buffered_docs_size", 0)
11651165

1166-
def _create_index(self, collection: Collection, index_key: Any, unique: bool) -> None:
1166+
def _create_index(self, collection: Collection[Any], index_key: Any, unique: bool) -> None:
11671167
doc = collection.find_one(projection={"_id": 1}, session=self._session)
11681168
if doc is None:
11691169
try:
@@ -1444,7 +1444,7 @@ class GridOut(GRIDOUT_BASE_CLASS): # type: ignore
14441444

14451445
def __init__(
14461446
self,
1447-
root_collection: Collection,
1447+
root_collection: Collection[Any],
14481448
file_id: Optional[int] = None,
14491449
file_document: Optional[Any] = None,
14501450
session: Optional[ClientSession] = None,
@@ -1817,7 +1817,7 @@ class GridOutChunkIterator:
18171817
def __init__(
18181818
self,
18191819
grid_out: GridOut,
1820-
chunks: Collection,
1820+
chunks: Collection[Any],
18211821
session: Optional[ClientSession],
18221822
next_chunk: Any,
18231823
) -> None:
@@ -1830,7 +1830,7 @@ def __init__(
18301830
self._num_chunks = math.ceil(float(self._length) / self._chunk_size)
18311831
self._cursor = None
18321832

1833-
_cursor: Optional[Cursor]
1833+
_cursor: Optional[Cursor[Any]]
18341834

18351835
def expected_chunk_length(self, chunk_n: int) -> int:
18361836
if chunk_n < self._num_chunks - 1:
@@ -1908,7 +1908,7 @@ def close(self) -> None:
19081908

19091909

19101910
class GridOutIterator:
1911-
def __init__(self, grid_out: GridOut, chunks: Collection, session: ClientSession):
1911+
def __init__(self, grid_out: GridOut, chunks: Collection[Any], session: ClientSession):
19121912
self._chunk_iter = GridOutChunkIterator(grid_out, chunks, session, 0)
19131913

19141914
def __iter__(self) -> GridOutIterator:
@@ -1921,14 +1921,14 @@ def next(self) -> bytes:
19211921
__next__ = next
19221922

19231923

1924-
class GridOutCursor(Cursor):
1924+
class GridOutCursor(Cursor): # type: ignore[type-arg]
19251925
"""A cursor / iterator for returning GridOut objects as the result
19261926
of an arbitrary query against the GridFS files collection.
19271927
"""
19281928

19291929
def __init__(
19301930
self,
1931-
collection: Collection,
1931+
collection: Collection[Any],
19321932
filter: Optional[Mapping[str, Any]] = None,
19331933
skip: int = 0,
19341934
limit: int = 0,

pymongo/_asyncio_lock.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin):
9393
"""
9494

9595
def __init__(self) -> None:
96-
self._waiters: Optional[collections.deque] = None
96+
self._waiters: Optional[collections.deque[Any]] = None
9797
self._locked = False
9898

9999
def __repr__(self) -> str:
@@ -196,7 +196,7 @@ def __init__(self, lock: Optional[Lock] = None) -> None:
196196
self.acquire = lock.acquire
197197
self.release = lock.release
198198

199-
self._waiters: collections.deque = collections.deque()
199+
self._waiters: collections.deque[Any] = collections.deque()
200200

201201
def __repr__(self) -> str:
202202
res = super().__repr__()
@@ -260,7 +260,7 @@ async def wait(self) -> bool:
260260
self._notify(1)
261261
raise
262262

263-
async def wait_for(self, predicate: Any) -> Coroutine:
263+
async def wait_for(self, predicate: Any) -> Coroutine[Any, Any, Any]:
264264
"""Wait until a predicate becomes true.
265265
266266
The predicate should be a callable whose result will be

pymongo/_asyncio_task.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525

2626
# TODO (https://jira.mongodb.org/browse/PYTHON-4981): Revisit once the underlying cause of the swallowed cancellations is uncovered
27-
class _Task(asyncio.Task):
27+
class _Task(asyncio.Task[Any]):
2828
def __init__(self, coro: Coroutine[Any, Any, Any], *, name: Optional[str] = None) -> None:
2929
super().__init__(coro, name=name)
3030
self._cancel_requests = 0
@@ -43,7 +43,7 @@ def cancelling(self) -> int:
4343
return self._cancel_requests
4444

4545

46-
def create_task(coro: Coroutine[Any, Any, Any], *, name: Optional[str] = None) -> asyncio.Task:
46+
def create_task(coro: Coroutine[Any, Any, Any], *, name: Optional[str] = None) -> asyncio.Task[Any]:
4747
if sys.version_info >= (3, 11):
4848
return asyncio.create_task(coro, name=name)
4949
return _Task(coro, name=name)

pymongo/_csot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def clamp_remaining(max_timeout: float) -> float:
6868
return min(timeout, max_timeout)
6969

7070

71-
class _TimeoutContext(AbstractContextManager):
71+
class _TimeoutContext(AbstractContextManager[Any]):
7272
"""Internal timeout context manager.
7373
7474
Use :func:`pymongo.timeout` instead::

0 commit comments

Comments
 (0)