Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bson/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import warnings
from collections.abc import Sequence
from enum import Enum
from typing import TYPE_CHECKING, Any, overload
from typing import TYPE_CHECKING, Any, Self, overload
from uuid import UUID

"""Tools for representing BSON binary data.
Expand Down Expand Up @@ -310,10 +310,10 @@ class Binary(bytes):
__subtype: int

def __new__(
cls: type[Binary],
cls,
data: memoryview | bytes | bytearray | _mmap | _array[Any],
subtype: int = BINARY_SUBTYPE,
) -> Binary:
) -> Self:
if not isinstance(subtype, int):
raise TypeError(f"subtype must be an instance of int, not {type(subtype)}")
if subtype >= 256 or subtype < 0:
Expand Down
6 changes: 3 additions & 3 deletions bson/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from collections.abc import Mapping
from collections.abc import Mapping as _Mapping
from typing import Any
from typing import Any, Self


class Code(str):
Expand Down Expand Up @@ -52,11 +52,11 @@ class Code(str):
__scope: Mapping[str, Any] | None

def __new__(
cls: type[Code],
cls,
code: str | Code,
scope: Mapping[str, Any] | None = None,
**kwargs: Any,
) -> Code:
) -> Self:
if not isinstance(code, str):
raise TypeError(f"code must be an instance of str, not {type(code)}")

Expand Down
5 changes: 3 additions & 2 deletions bson/codec_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
Any,
Generic,
NamedTuple,
Self,
cast,
)

Expand Down Expand Up @@ -368,15 +369,15 @@ def __init__(self, *args, **kwargs):
super().__init__()

def __new__(
cls: type[CodecOptions],
cls,
document_class: type[Mapping[str, Any]] | None = None,
tz_aware: bool = False,
uuid_representation: int | None = UuidRepresentation.UNSPECIFIED,
unicode_decode_error_handler: str = "strict",
tzinfo: datetime.tzinfo | None = None,
type_registry: TypeRegistry | None = None,
datetime_conversion: DatetimeConversion | None = DatetimeConversion.DATETIME,
) -> CodecOptions:
) -> Self:
doc_class = document_class or dict
# Generic aliases like SON[str, Any] or dict[str, Any] aren't classes, so
# resolve to their origin before the subclass check. issubclass() raises
Expand Down
7 changes: 4 additions & 3 deletions bson/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
from typing import (
TYPE_CHECKING,
Any,
Self,
cast,
)

Expand Down Expand Up @@ -300,14 +301,14 @@ def __init__(self, *args: Any, **kwargs: Any):
super().__init__()

def __new__(
cls: type[JSONOptions],
cls,
strict_number_long: bool | None = None,
datetime_representation: int | None = None,
strict_uuid: bool | None = None,
json_mode: int = JSONMode.RELAXED,
*args: Any,
**kwargs: Any,
) -> JSONOptions:
) -> Self:
kwargs["tz_aware"] = kwargs.get("tz_aware", False)
if kwargs["tz_aware"]:
kwargs["tzinfo"] = kwargs.get("tzinfo", utc)
Expand All @@ -321,7 +322,7 @@ def __new__(
"JSONOptions.datetime_representation must be one of LEGACY, "
"NUMBERLONG, or ISO8601 from DatetimeRepresentation."
)
self = cast(JSONOptions, super().__new__(cls, *args, **kwargs))
self = cast(Self, super().__new__(cls, *args, **kwargs))
if json_mode not in (JSONMode.LEGACY, JSONMode.RELAXED, JSONMode.CANONICAL):
raise ValueError(
"JSONOptions.json_mode must be one of LEGACY, RELAXED, or CANONICAL from JSONMode."
Expand Down
4 changes: 2 additions & 2 deletions bson/typings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@

# Common Shared Types.
_DocumentOut = Union[MutableMapping[str, Any], "RawBSONDocument"]
_DocumentType = TypeVar("_DocumentType", bound=Mapping[str, Any])
_DocumentTypeArg = TypeVar("_DocumentTypeArg", bound=Mapping[str, Any])
_DocumentType = TypeVar("_DocumentType", bound=Mapping[str, Any]) # noqa: PYI018
_DocumentTypeArg = TypeVar("_DocumentTypeArg", bound=Mapping[str, Any]) # noqa: PYI018
_ReadableBuffer = Union[bytes, memoryview, bytearray, "mmap", "array"] # type: ignore[type-arg]
21 changes: 16 additions & 5 deletions gridfs/asynchronous/grid_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
import math
from collections import abc
from collections.abc import Iterable, Mapping
from typing import Any, NoReturn, cast
from types import TracebackType
from typing import Any, NoReturn, Self, cast

from bson.int64 import Int64
from bson.objectid import ObjectId
Expand Down Expand Up @@ -1438,11 +1439,16 @@ async def writelines(self, sequence: Iterable[Any]) -> None:
def writeable(self) -> bool:
return True

async def __aenter__(self) -> AsyncGridIn:
async def __aenter__(self) -> Self:
"""Support for the context manager protocol."""
return self

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> Any:
"""Support for the context manager protocol.

Close the file if no exceptions occur and allow exceptions to propagate.
Expand Down Expand Up @@ -1796,13 +1802,18 @@ def writelines(self, lines: Any) -> NoReturn:
def writable(self) -> bool:
return False

async def __aenter__(self) -> AsyncGridOut:
async def __aenter__(self) -> Self:
"""Makes it possible to use :class:`AsyncGridOut` files
with the async context manager protocol.
"""
return self

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> Any:
"""Makes it possible to use :class:`AsyncGridOut` files
with the async context manager protocol.
"""
Expand Down
21 changes: 16 additions & 5 deletions gridfs/synchronous/grid_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
import math
from collections import abc
from collections.abc import Iterable, Mapping
from typing import Any, NoReturn, cast
from types import TracebackType
from typing import Any, NoReturn, Self, cast

from bson.int64 import Int64
from bson.objectid import ObjectId
Expand Down Expand Up @@ -1420,11 +1421,16 @@ def writelines(self, sequence: Iterable[Any]) -> None:
def writeable(self) -> bool:
return True

def __enter__(self) -> GridIn:
def __enter__(self) -> Self:
"""Support for the context manager protocol."""
return self

def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any:
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> Any:
"""Support for the context manager protocol.

Close the file if no exceptions occur and allow exceptions to propagate.
Expand Down Expand Up @@ -1778,13 +1784,18 @@ def writelines(self, lines: Any) -> NoReturn:
def writable(self) -> bool:
return False

def __enter__(self) -> GridOut:
def __enter__(self) -> Self:
"""Makes it possible to use :class:`GridOut` files
with the async context manager protocol.
"""
return self

def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any:
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> Any:
"""Makes it possible to use :class:`GridOut` files
with the async context manager protocol.
"""
Expand Down
8 changes: 7 additions & 1 deletion pymongo/_asyncio_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import threading
from asyncio import events, exceptions
from collections.abc import Coroutine
from types import TracebackType
from typing import Any

_global_lock = threading.Lock()
Expand Down Expand Up @@ -37,7 +38,12 @@ async def __aenter__(self) -> None:
# statement for locks.
return

async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
self.release() # type: ignore[attr-defined]


Expand Down
8 changes: 7 additions & 1 deletion pymongo/_csot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from collections.abc import Callable, MutableMapping
from contextlib import AbstractContextManager
from contextvars import ContextVar, Token
from types import TracebackType
from typing import TYPE_CHECKING, Any, TypeVar, cast

if TYPE_CHECKING:
Expand Down Expand Up @@ -90,7 +91,12 @@ def __enter__(self) -> None:
rtt_token = RTT.set(0.0)
self._tokens = (timeout_token, deadline_token, rtt_token)

def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self._tokens:
timeout_token, deadline_token, rtt_token = self._tokens
TIMEOUT.reset(timeout_token)
Expand Down
8 changes: 7 additions & 1 deletion pymongo/_op_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from contextlib import AbstractContextManager
from contextvars import ContextVar
from types import TracebackType
from typing import Any

OP_ID: ContextVar[int | None] = ContextVar("OP_ID", default=None)
Expand All @@ -42,5 +43,10 @@ def __init__(self, op_id: int | None):
def __enter__(self) -> None:
self._token = OP_ID.set(self._op_id)

def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
OP_ID.reset(self._token)
10 changes: 8 additions & 2 deletions pymongo/asynchronous/change_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Any
from types import TracebackType
from typing import TYPE_CHECKING

from bson import _bson_to_dict
from pymongo import _csot
Expand Down Expand Up @@ -246,7 +247,12 @@ async def try_next(self) -> _DocumentType | None:
async def __aenter__(self) -> AsyncChangeStream[_DocumentType]:
return self

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
await self.close()


Expand Down
19 changes: 15 additions & 4 deletions pymongo/asynchronous/client_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
from typing import (
TYPE_CHECKING,
Any,
Self,
TypeVar,
)

Expand Down Expand Up @@ -197,7 +198,12 @@ async def __aenter__(self) -> AsyncClientSession:
self._session_token = _SESSION.set(self._session) # type: ignore[assignment]
return self._session

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self._session_token:
_SESSION.reset(self._session_token) # type: ignore[arg-type]
self._session_token = None
Expand All @@ -211,7 +217,7 @@ class _TransactionContext:
def __init__(self, session: AsyncClientSession):
self.__session = session

async def __aenter__(self) -> _TransactionContext:
async def __aenter__(self) -> Self:
return self

async def __aexit__(
Expand Down Expand Up @@ -292,10 +298,15 @@ async def _end_session(self, lock: bool) -> None:
self._client._return_server_session(self._server_session)
self._server_session = None

async def __aenter__(self) -> AsyncClientSession:
async def __aenter__(self) -> Self:
return self

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
await self._end_session(lock=True)

async def with_transaction(
Expand Down
8 changes: 7 additions & 1 deletion pymongo/asynchronous/cursor_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

from abc import abstractmethod
from collections.abc import Mapping, Sequence
from types import TracebackType
from typing import TYPE_CHECKING, Any, cast

from pymongo import _csot
Expand Down Expand Up @@ -187,7 +188,12 @@ async def close(self) -> None:
"""Explicitly close / kill this cursor."""
await self._die_lock()

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
await self.close()

@_csot.apply
Expand Down
8 changes: 7 additions & 1 deletion pymongo/asynchronous/encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import weakref
from collections.abc import AsyncGenerator, Mapping, MutableMapping, Sequence
from copy import deepcopy
from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -1160,7 +1161,12 @@ async def rewrap_many_data_key(
async def __aenter__(self) -> AsyncClientEncryption[_DocumentType]:
return self

async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
await self.close()

def _check_closed(self) -> None:
Expand Down
Loading
Loading