diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 9469081ae5d6..6937d97b87ea 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -47,10 +47,15 @@ AnyStr_co = TypeVar("AnyStr_co", str, bytes, covariant=True) # noqa: Y001 # isn't possible or a type is already partially known. In cases like these, # use Incomplete instead of Any as a marker. For example, use # "Incomplete | None" instead of "Any | None". -Incomplete: TypeAlias = Any +Incomplete: TypeAlias = Any # stable # To describe a function parameter that is unused and will work with anything. -Unused: TypeAlias = object +Unused: TypeAlias = object # stable + +# Marker for return types that include None, but where forcing the user to +# check for None can be detrimental. Sometimes called "the Any trick". See +# CONTRIBUTING.md for more information. +MaybeNone: TypeAlias = Any # stable # Used to mark arguments that default to a sentinel value. This prevents # stubtest from complaining about the default value not matching. @@ -146,13 +151,22 @@ class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... def __getitem__(self, key: _KT, /) -> _VT_co: ... -# stable +# This protocol is currently under discussion. Use SupportsContainsAndGetItem +# instead, if you require the __contains__ method. +# See https://github.com/python/typeshed/issues/11822. class SupportsGetItem(Protocol[_KT_contra, _VT_co]): def __contains__(self, x: Any, /) -> bool: ... def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... # stable -class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, _VT]): +class SupportsContainsAndGetItem(Protocol[_KT_contra, _VT_co]): + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... + +# stable +class SupportsItemAccess(Protocol[_KT_contra, _VT]): + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT: ... def __setitem__(self, key: _KT_contra, value: _VT, /) -> None: ... def __delitem__(self, key: _KT_contra, /) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/constants.pyi b/mypy/typeshed/stdlib/asyncio/constants.pyi index 559cc02a0faa..7759a2844953 100644 --- a/mypy/typeshed/stdlib/asyncio/constants.pyi +++ b/mypy/typeshed/stdlib/asyncio/constants.pyi @@ -15,6 +15,6 @@ if sys.version_info >= (3, 12): THREAD_JOIN_TIMEOUT: Literal[300] class _SendfileMode(enum.Enum): - UNSUPPORTED: int - TRY_NATIVE: int - FALLBACK: int + UNSUPPORTED = 1 + TRY_NATIVE = 2 + FALLBACK = 3 diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index e92b150875f6..bc797de7fd51 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Awaitable, Callable, Coroutine from typing import Any, TypeVar, overload -from typing_extensions import ParamSpec, TypeGuard +from typing_extensions import ParamSpec, TypeGuard, TypeIs if sys.version_info >= (3, 11): __all__ = ("iscoroutinefunction", "iscoroutine") @@ -23,4 +23,4 @@ def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... @overload def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... -def iscoroutine(obj: object) -> TypeGuard[Coroutine[Any, Any, Any]]: ... +def iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index 560dcc1d5712..a3953cdaf8c7 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -3,7 +3,7 @@ from collections.abc import Awaitable, Callable, Generator, Iterable from concurrent.futures._base import Future as _ConcurrentFuture from contextvars import Context from typing import Any, Literal, TypeVar -from typing_extensions import Self, TypeGuard +from typing_extensions import Self, TypeIs from .events import AbstractEventLoop @@ -17,7 +17,7 @@ _T = TypeVar("_T") # asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py # but it leads to circular import error in pytype tool. # That's why the import order is reversed. -def isfuture(obj: object) -> TypeGuard[Future[Any]]: ... +def isfuture(obj: object) -> TypeIs[Future[Any]]: ... class Future(Awaitable[_T], Iterable[_T]): _state: str diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 3aac34b6934f..0114aeb23329 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -101,10 +101,10 @@ class BoundedSemaphore(Semaphore): ... if sys.version_info >= (3, 11): class _BarrierState(enum.Enum): # undocumented - FILLING: str - DRAINING: str - RESETTING: str - BROKEN: str + FILLING = "filling" + DRAINING = "draining" + RESETTING = "resetting" + BROKEN = "broken" class Barrier(_LoopBoundMixin): def __init__(self, parties: int) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 04197c8d2978..e904d7395cdc 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -14,17 +14,17 @@ if sys.version_info >= (3, 11): SSLAgainErrors: tuple[type[ssl.SSLWantReadError], type[ssl.SSLSyscallError]] class SSLProtocolState(Enum): - UNWRAPPED: str - DO_HANDSHAKE: str - WRAPPED: str - FLUSHING: str - SHUTDOWN: str + UNWRAPPED = "UNWRAPPED" + DO_HANDSHAKE = "DO_HANDSHAKE" + WRAPPED = "WRAPPED" + FLUSHING = "FLUSHING" + SHUTDOWN = "SHUTDOWN" class AppProtocolState(Enum): - STATE_INIT: str - STATE_CON_MADE: str - STATE_EOF: str - STATE_CON_LOST: str + STATE_INIT = "STATE_INIT" + STATE_CON_MADE = "STATE_CON_MADE" + STATE_EOF = "STATE_EOF" + STATE_CON_LOST = "STATE_CON_LOST" def add_flowcontrol_defaults(high: int | None, low: int | None, kb: int) -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi index 830d6f83a273..f3ce78ccb7fa 100644 --- a/mypy/typeshed/stdlib/audioop.pyi +++ b/mypy/typeshed/stdlib/audioop.pyi @@ -1,32 +1,32 @@ -from typing_extensions import TypeAlias +from typing_extensions import Buffer, TypeAlias _AdpcmState: TypeAlias = tuple[int, int] _RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... -def add(fragment1: bytes, fragment2: bytes, width: int, /) -> bytes: ... -def adpcm2lin(fragment: bytes, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... -def alaw2lin(fragment: bytes, width: int, /) -> bytes: ... -def avg(fragment: bytes, width: int, /) -> int: ... -def avgpp(fragment: bytes, width: int, /) -> int: ... -def bias(fragment: bytes, width: int, bias: int, /) -> bytes: ... -def byteswap(fragment: bytes, width: int, /) -> bytes: ... -def cross(fragment: bytes, width: int, /) -> int: ... -def findfactor(fragment: bytes, reference: bytes, /) -> float: ... -def findfit(fragment: bytes, reference: bytes, /) -> tuple[int, float]: ... -def findmax(fragment: bytes, length: int, /) -> int: ... -def getsample(fragment: bytes, width: int, index: int, /) -> int: ... -def lin2adpcm(fragment: bytes, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... -def lin2alaw(fragment: bytes, width: int, /) -> bytes: ... -def lin2lin(fragment: bytes, width: int, newwidth: int, /) -> bytes: ... -def lin2ulaw(fragment: bytes, width: int, /) -> bytes: ... -def max(fragment: bytes, width: int, /) -> int: ... -def maxpp(fragment: bytes, width: int, /) -> int: ... -def minmax(fragment: bytes, width: int, /) -> tuple[int, int]: ... -def mul(fragment: bytes, width: int, factor: float, /) -> bytes: ... +def add(fragment1: Buffer, fragment2: Buffer, width: int, /) -> bytes: ... +def adpcm2lin(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def alaw2lin(fragment: Buffer, width: int, /) -> bytes: ... +def avg(fragment: Buffer, width: int, /) -> int: ... +def avgpp(fragment: Buffer, width: int, /) -> int: ... +def bias(fragment: Buffer, width: int, bias: int, /) -> bytes: ... +def byteswap(fragment: Buffer, width: int, /) -> bytes: ... +def cross(fragment: Buffer, width: int, /) -> int: ... +def findfactor(fragment: Buffer, reference: Buffer, /) -> float: ... +def findfit(fragment: Buffer, reference: Buffer, /) -> tuple[int, float]: ... +def findmax(fragment: Buffer, length: int, /) -> int: ... +def getsample(fragment: Buffer, width: int, index: int, /) -> int: ... +def lin2adpcm(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def lin2alaw(fragment: Buffer, width: int, /) -> bytes: ... +def lin2lin(fragment: Buffer, width: int, newwidth: int, /) -> bytes: ... +def lin2ulaw(fragment: Buffer, width: int, /) -> bytes: ... +def max(fragment: Buffer, width: int, /) -> int: ... +def maxpp(fragment: Buffer, width: int, /) -> int: ... +def minmax(fragment: Buffer, width: int, /) -> tuple[int, int]: ... +def mul(fragment: Buffer, width: int, factor: float, /) -> bytes: ... def ratecv( - fragment: bytes, + fragment: Buffer, width: int, nchannels: int, inrate: int, @@ -36,8 +36,8 @@ def ratecv( weightB: int = 0, /, ) -> tuple[bytes, _RatecvState]: ... -def reverse(fragment: bytes, width: int, /) -> bytes: ... -def rms(fragment: bytes, width: int, /) -> int: ... -def tomono(fragment: bytes, width: int, lfactor: float, rfactor: float, /) -> bytes: ... -def tostereo(fragment: bytes, width: int, lfactor: float, rfactor: float, /) -> bytes: ... -def ulaw2lin(fragment: bytes, width: int, /) -> bytes: ... +def reverse(fragment: Buffer, width: int, /) -> bytes: ... +def rms(fragment: Buffer, width: int, /) -> int: ... +def tomono(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def tostereo(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def ulaw2lin(fragment: Buffer, width: int, /) -> bytes: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 47dddcadf36d..9e56c5430c52 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -65,6 +65,7 @@ from typing_extensions import ( # noqa: Y023 Self, TypeAlias, TypeGuard, + TypeIs, TypeVarTuple, deprecated, ) @@ -943,15 +944,25 @@ class dict(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... + def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 @overload def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload - def __init__(self: dict[str, _VT], map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ... + def __init__( + self: dict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + map: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... @overload def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload - def __init__(self: dict[str, _VT], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... + def __init__( + self: dict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... # Next two overloads are for dict(string.split(sep) for string in iterable) # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload @@ -1143,7 +1154,7 @@ def any(iterable: Iterable[object], /) -> bool: ... def ascii(obj: object, /) -> str: ... def bin(number: int | SupportsIndex, /) -> str: ... def breakpoint(*args: Any, **kws: Any) -> None: ... -def callable(obj: object, /) -> TypeGuard[Callable[..., object]]: ... +def callable(obj: object, /) -> TypeIs[Callable[..., object]]: ... def chr(i: int, /) -> str: ... # We define this here instead of using os.PathLike to avoid import cycle issues. @@ -1253,6 +1264,8 @@ class filter(Iterator[_T]): @overload def __new__(cls, function: Callable[[_S], TypeGuard[_T]], iterable: Iterable[_S], /) -> Self: ... @overload + def __new__(cls, function: Callable[[_S], TypeIs[_T]], iterable: Iterable[_S], /) -> Self: ... + @overload def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index d20be33e3d76..3a2e2a91b241 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,4 +1,4 @@ -from _typeshed import SupportsGetItem, SupportsItemAccess, Unused +from _typeshed import SupportsContainsAndGetItem, SupportsGetItem, SupportsItemAccess, Unused from builtins import list as _list, type as _type from collections.abc import Iterable, Iterator, Mapping from email.message import Message @@ -85,7 +85,7 @@ class FieldStorage: fp: IO[Any] | None = None, headers: Mapping[str, str] | Message | None = None, outerboundary: bytes = b"", - environ: SupportsGetItem[str, str] = ..., + environ: SupportsContainsAndGetItem[str, str] = ..., keep_blank_values: int = 0, strict_parsing: int = 0, limit: int | None = None, diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 1d23ecd66a8d..71e3c564dd57 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -51,15 +51,27 @@ class UserDict(MutableMapping[_KT, _VT]): @overload def __init__(self, dict: None = None, /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], dict: None = None, /, **kwargs: _VT) -> None: ... + def __init__( + self: UserDict[str, _VT], dict: None = None, /, **kwargs: _VT # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... @overload def __init__(self, dict: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], dict: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ... + def __init__( + self: UserDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + dict: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... @overload def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload - def __init__(self: UserDict[str, _VT], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... + def __init__( + self: UserDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... @overload def __init__(self: UserDict[str, str], iterable: Iterable[list[str]], /) -> None: ... @overload @@ -389,16 +401,21 @@ class defaultdict(dict[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... + def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 @overload def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ... @overload - def __init__(self: defaultdict[str, _VT], default_factory: Callable[[], _VT] | None, /, **kwargs: _VT) -> None: ... + def __init__( + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + /, + **kwargs: _VT, + ) -> None: ... @overload def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... @overload def __init__( - self: defaultdict[str, _VT], + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[str, _VT], /, @@ -408,7 +425,7 @@ class defaultdict(dict[_KT, _VT]): def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... @overload def __init__( - self: defaultdict[str, _VT], + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[str, _VT]], /, diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index f82bb4b7b6ad..29ac7cde561a 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -31,32 +31,33 @@ if sys.version_info >= (3, 11): _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_io = TypeVar("_T_io", bound=IO[str] | None) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound=bool | None, default=bool | None) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") _ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] -_CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any] | _ExitFunc) +_CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any, Any] | _ExitFunc) @runtime_checkable -class AbstractContextManager(Protocol[_T_co]): +class AbstractContextManager(Protocol[_T_co, _ExitT_co]): def __enter__(self) -> _T_co: ... @abstractmethod def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / - ) -> bool | None: ... + ) -> _ExitT_co: ... @runtime_checkable -class AbstractAsyncContextManager(Protocol[_T_co]): +class AbstractAsyncContextManager(Protocol[_T_co, _ExitT_co]): async def __aenter__(self) -> _T_co: ... @abstractmethod async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / - ) -> bool | None: ... + ) -> _ExitT_co: ... class ContextDecorator: def __call__(self, func: _F) -> _F: ... -class _GeneratorContextManager(AbstractContextManager[_T_co], ContextDecorator): +class _GeneratorContextManager(AbstractContextManager[_T_co, bool | None], ContextDecorator): # __init__ and all instance attributes are actually inherited from _GeneratorContextManagerBase # _GeneratorContextManagerBase is more trouble than it's worth to include in the stub; see #6676 def __init__(self, func: Callable[..., Iterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... @@ -81,7 +82,7 @@ if sys.version_info >= (3, 10): class AsyncContextDecorator: def __call__(self, func: _AF) -> _AF: ... - class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co], AsyncContextDecorator): + class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co, bool | None], AsyncContextDecorator): # __init__ and these attributes are actually defined in the base class _GeneratorContextManagerBase, # which is more trouble than it's worth to include in the stub (see #6676) def __init__(self, func: Callable[..., AsyncIterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... @@ -94,7 +95,7 @@ if sys.version_info >= (3, 10): ) -> bool | None: ... else: - class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co]): + class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co, bool | None]): def __init__(self, func: Callable[..., AsyncIterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... gen: AsyncGenerator[_T_co, Any] func: Callable[..., AsyncGenerator[_T_co, Any]] @@ -111,7 +112,7 @@ class _SupportsClose(Protocol): _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) -class closing(AbstractContextManager[_SupportsCloseT]): +class closing(AbstractContextManager[_SupportsCloseT, None]): def __init__(self, thing: _SupportsCloseT) -> None: ... def __exit__(self, *exc_info: Unused) -> None: ... @@ -121,17 +122,17 @@ if sys.version_info >= (3, 10): _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) - class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): + class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]): def __init__(self, thing: _SupportsAcloseT) -> None: ... async def __aexit__(self, *exc_info: Unused) -> None: ... -class suppress(AbstractContextManager[None]): +class suppress(AbstractContextManager[None, bool]): def __init__(self, *exceptions: type[BaseException]) -> None: ... def __exit__( self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None ) -> bool: ... -class _RedirectStream(AbstractContextManager[_T_io]): +class _RedirectStream(AbstractContextManager[_T_io, None]): def __init__(self, new_target: _T_io) -> None: ... def __exit__( self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None @@ -142,8 +143,8 @@ class redirect_stderr(_RedirectStream[_T_io]): ... # In reality this is a subclass of `AbstractContextManager`; # see #7961 for why we don't do that in the stub -class ExitStack(metaclass=abc.ABCMeta): - def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... +class ExitStack(Generic[_ExitT_co], metaclass=abc.ABCMeta): + def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... def pop_all(self) -> Self: ... @@ -151,18 +152,18 @@ class ExitStack(metaclass=abc.ABCMeta): def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / - ) -> bool: ... + ) -> _ExitT_co: ... _ExitCoroFunc: TypeAlias = Callable[ [type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool | None] ] -_ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any] | _ExitCoroFunc) +_ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any, Any] | _ExitCoroFunc) # In reality this is a subclass of `AbstractAsyncContextManager`; # see #7961 for why we don't do that in the stub -class AsyncExitStack(metaclass=abc.ABCMeta): - def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... - async def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... +class AsyncExitStack(Generic[_ExitT_co], metaclass=abc.ABCMeta): + def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: ... + async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... @@ -177,31 +178,31 @@ class AsyncExitStack(metaclass=abc.ABCMeta): ) -> bool: ... if sys.version_info >= (3, 10): - class nullcontext(AbstractContextManager[_T], AbstractAsyncContextManager[_T]): + class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]): enter_result: _T @overload def __init__(self: nullcontext[None], enter_result: None = None) -> None: ... @overload - def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 def __enter__(self) -> _T: ... def __exit__(self, *exctype: Unused) -> None: ... async def __aenter__(self) -> _T: ... async def __aexit__(self, *exctype: Unused) -> None: ... else: - class nullcontext(AbstractContextManager[_T]): + class nullcontext(AbstractContextManager[_T, None]): enter_result: _T @overload def __init__(self: nullcontext[None], enter_result: None = None) -> None: ... @overload - def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 def __enter__(self) -> _T: ... def __exit__(self, *exctype: Unused) -> None: ... if sys.version_info >= (3, 11): _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=FileDescriptorOrPath) - class chdir(AbstractContextManager[None], Generic[_T_fd_or_any_path]): + class chdir(AbstractContextManager[None, None], Generic[_T_fd_or_any_path]): path: _T_fd_or_any_path def __init__(self, path: _T_fd_or_any_path) -> None: ... def __enter__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index d7d7e8c8e908..4032bc6136d4 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -3,22 +3,25 @@ from email import _ParamsType, _ParamType from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect -from email.header import Header from email.policy import Policy -from typing import Any, Literal, Protocol, TypeVar, overload +from typing import Any, Generic, Literal, Protocol, TypeVar, overload from typing_extensions import Self, TypeAlias __all__ = ["Message", "EmailMessage"] _T = TypeVar("_T") +# Type returned by Policy.header_fetch_parse, often str or Header. +_HeaderT = TypeVar("_HeaderT", default=str) +_HeaderParamT = TypeVar("_HeaderParamT", default=str) +# Represents headers constructed by HeaderRegistry. Those are sub-classes +# of BaseHeader and another header type. +_HeaderRegistryT = TypeVar("_HeaderRegistryT", default=Any) +_HeaderRegistryParamT = TypeVar("_HeaderRegistryParamT", default=Any) + _PayloadType: TypeAlias = Message | str _EncodedPayloadType: TypeAlias = Message | bytes _MultipartPayloadType: TypeAlias = list[_PayloadType] _CharsetType: TypeAlias = Charset | str | None -# Type returned by Policy.header_fetch_parse, often str or Header. -_HeaderType: TypeAlias = Any -# Type accepted by Policy.header_store_parse. -_HeaderTypeParam: TypeAlias = str | Header | Any class _SupportsEncodeToPayload(Protocol): def encode(self, encoding: str, /) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ... @@ -26,10 +29,7 @@ class _SupportsEncodeToPayload(Protocol): class _SupportsDecodeToPayload(Protocol): def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ... -# TODO: This class should be generic over the header policy and/or the header -# value types allowed by the policy. This depends on PEP 696 support -# (https://github.com/python/typeshed/issues/11422). -class Message: +class Message(Generic[_HeaderT, _HeaderParamT]): policy: Policy # undocumented preamble: str | None epilogue: str | None @@ -70,24 +70,23 @@ class Message: # Same as `get` with `failobj=None`, but with the expectation that it won't return None in most scenarios # This is important for protocols using __getitem__, like SupportsKeysAndGetItem # Morally, the return type should be `AnyOf[_HeaderType, None]`, - # which we could spell as `_HeaderType | Any`, - # *but* `_HeaderType` itself is currently an alias to `Any`... - def __getitem__(self, name: str) -> _HeaderType: ... - def __setitem__(self, name: str, val: _HeaderTypeParam) -> None: ... + # so using "the Any trick" instead. + def __getitem__(self, name: str) -> _HeaderT | Any: ... + def __setitem__(self, name: str, val: _HeaderParamT) -> None: ... def __delitem__(self, name: str) -> None: ... def keys(self) -> list[str]: ... - def values(self) -> list[_HeaderType]: ... - def items(self) -> list[tuple[str, _HeaderType]]: ... + def values(self) -> list[_HeaderT]: ... + def items(self) -> list[tuple[str, _HeaderT]]: ... @overload - def get(self, name: str, failobj: None = None) -> _HeaderType | None: ... + def get(self, name: str, failobj: None = None) -> _HeaderT | None: ... @overload - def get(self, name: str, failobj: _T) -> _HeaderType | _T: ... + def get(self, name: str, failobj: _T) -> _HeaderT | _T: ... @overload - def get_all(self, name: str, failobj: None = None) -> list[_HeaderType] | None: ... + def get_all(self, name: str, failobj: None = None) -> list[_HeaderT] | None: ... @overload - def get_all(self, name: str, failobj: _T) -> list[_HeaderType] | _T: ... + def get_all(self, name: str, failobj: _T) -> list[_HeaderT] | _T: ... def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ... - def replace_header(self, _name: str, _value: _HeaderTypeParam) -> None: ... + def replace_header(self, _name: str, _value: _HeaderParamT) -> None: ... def get_content_type(self) -> str: ... def get_content_maintype(self) -> str: ... def get_content_subtype(self) -> str: ... @@ -141,14 +140,14 @@ class Message: ) -> None: ... def __init__(self, policy: Policy = ...) -> None: ... # The following two methods are undocumented, but a source code comment states that they are public API - def set_raw(self, name: str, value: _HeaderTypeParam) -> None: ... - def raw_items(self) -> Iterator[tuple[str, _HeaderType]]: ... + def set_raw(self, name: str, value: _HeaderParamT) -> None: ... + def raw_items(self) -> Iterator[tuple[str, _HeaderT]]: ... -class MIMEPart(Message): +class MIMEPart(Message[_HeaderRegistryT, _HeaderRegistryParamT]): def __init__(self, policy: Policy | None = None) -> None: ... - def get_body(self, preferencelist: Sequence[str] = ("related", "html", "plain")) -> Message | None: ... - def iter_attachments(self) -> Iterator[Message]: ... - def iter_parts(self) -> Iterator[Message]: ... + def get_body(self, preferencelist: Sequence[str] = ("related", "html", "plain")) -> MIMEPart[_HeaderRegistryT] | None: ... + def iter_attachments(self) -> Iterator[MIMEPart[_HeaderRegistryT]]: ... + def iter_parts(self) -> Iterator[MIMEPart[_HeaderRegistryT]]: ... def get_content(self, *args: Any, content_manager: ContentManager | None = None, **kw: Any) -> Any: ... def set_content(self, *args: Any, content_manager: ContentManager | None = None, **kw: Any) -> None: ... def make_related(self, boundary: str | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index 28b6aca856ca..fecb29d90b2e 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -3,24 +3,34 @@ from collections.abc import Callable from email.feedparser import BytesFeedParser as BytesFeedParser, FeedParser as FeedParser from email.message import Message from email.policy import Policy -from typing import IO +from io import _WrappedBuffer +from typing import Generic, TypeVar, overload __all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedParser", "BytesFeedParser"] -class Parser: - def __init__(self, _class: Callable[[], Message] | None = None, *, policy: Policy = ...) -> None: ... - def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> Message: ... - def parsestr(self, text: str, headersonly: bool = False) -> Message: ... +_MessageT = TypeVar("_MessageT", bound=Message, default=Message) -class HeaderParser(Parser): - def parse(self, fp: SupportsRead[str], headersonly: bool = True) -> Message: ... - def parsestr(self, text: str, headersonly: bool = True) -> Message: ... +class Parser(Generic[_MessageT]): + @overload + def __init__(self: Parser[Message[str, str]], _class: None = None, *, policy: Policy = ...) -> None: ... + @overload + def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy = ...) -> None: ... + def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> _MessageT: ... + def parsestr(self, text: str, headersonly: bool = False) -> _MessageT: ... -class BytesParser: - def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... - def parse(self, fp: IO[bytes], headersonly: bool = False) -> Message: ... - def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> Message: ... +class HeaderParser(Parser[_MessageT]): + def parse(self, fp: SupportsRead[str], headersonly: bool = True) -> _MessageT: ... + def parsestr(self, text: str, headersonly: bool = True) -> _MessageT: ... -class BytesHeaderParser(BytesParser): - def parse(self, fp: IO[bytes], headersonly: bool = True) -> Message: ... - def parsebytes(self, text: bytes | bytearray, headersonly: bool = True) -> Message: ... +class BytesParser(Generic[_MessageT]): + parser: Parser[_MessageT] + @overload + def __init__(self: BytesParser[Message[str, str]], _class: None = None, *, policy: Policy = ...) -> None: ... + @overload + def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy = ...) -> None: ... + def parse(self, fp: _WrappedBuffer, headersonly: bool = False) -> _MessageT: ... + def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> _MessageT: ... + +class BytesHeaderParser(BytesParser[_MessageT]): + def parse(self, fp: _WrappedBuffer, headersonly: bool = True) -> _MessageT: ... + def parsebytes(self, text: bytes | bytearray, headersonly: bool = True) -> _MessageT: ... diff --git a/mypy/typeshed/stdlib/http/__init__.pyi b/mypy/typeshed/stdlib/http/__init__.pyi index 2eee06fdaaa9..bb5737cc0481 100644 --- a/mypy/typeshed/stdlib/http/__init__.pyi +++ b/mypy/typeshed/stdlib/http/__init__.pyi @@ -15,65 +15,65 @@ class HTTPStatus(IntEnum): def phrase(self) -> str: ... @property def description(self) -> str: ... - CONTINUE: int - SWITCHING_PROTOCOLS: int - PROCESSING: int - OK: int - CREATED: int - ACCEPTED: int - NON_AUTHORITATIVE_INFORMATION: int - NO_CONTENT: int - RESET_CONTENT: int - PARTIAL_CONTENT: int - MULTI_STATUS: int - ALREADY_REPORTED: int - IM_USED: int - MULTIPLE_CHOICES: int - MOVED_PERMANENTLY: int - FOUND: int - SEE_OTHER: int - NOT_MODIFIED: int - USE_PROXY: int - TEMPORARY_REDIRECT: int - PERMANENT_REDIRECT: int - BAD_REQUEST: int - UNAUTHORIZED: int - PAYMENT_REQUIRED: int - FORBIDDEN: int - NOT_FOUND: int - METHOD_NOT_ALLOWED: int - NOT_ACCEPTABLE: int - PROXY_AUTHENTICATION_REQUIRED: int - REQUEST_TIMEOUT: int - CONFLICT: int - GONE: int - LENGTH_REQUIRED: int - PRECONDITION_FAILED: int - REQUEST_ENTITY_TOO_LARGE: int - REQUEST_URI_TOO_LONG: int - UNSUPPORTED_MEDIA_TYPE: int - REQUESTED_RANGE_NOT_SATISFIABLE: int - EXPECTATION_FAILED: int - UNPROCESSABLE_ENTITY: int - LOCKED: int - FAILED_DEPENDENCY: int - UPGRADE_REQUIRED: int - PRECONDITION_REQUIRED: int - TOO_MANY_REQUESTS: int - REQUEST_HEADER_FIELDS_TOO_LARGE: int - INTERNAL_SERVER_ERROR: int - NOT_IMPLEMENTED: int - BAD_GATEWAY: int - SERVICE_UNAVAILABLE: int - GATEWAY_TIMEOUT: int - HTTP_VERSION_NOT_SUPPORTED: int - VARIANT_ALSO_NEGOTIATES: int - INSUFFICIENT_STORAGE: int - LOOP_DETECTED: int - NOT_EXTENDED: int - NETWORK_AUTHENTICATION_REQUIRED: int - MISDIRECTED_REQUEST: int - UNAVAILABLE_FOR_LEGAL_REASONS: int + CONTINUE = 100 + SWITCHING_PROTOCOLS = 101 + PROCESSING = 102 + OK = 200 + CREATED = 201 + ACCEPTED = 202 + NON_AUTHORITATIVE_INFORMATION = 203 + NO_CONTENT = 204 + RESET_CONTENT = 205 + PARTIAL_CONTENT = 206 + MULTI_STATUS = 207 + ALREADY_REPORTED = 208 + IM_USED = 226 + MULTIPLE_CHOICES = 300 + MOVED_PERMANENTLY = 301 + FOUND = 302 + SEE_OTHER = 303 + NOT_MODIFIED = 304 + USE_PROXY = 305 + TEMPORARY_REDIRECT = 307 + PERMANENT_REDIRECT = 308 + BAD_REQUEST = 400 + UNAUTHORIZED = 401 + PAYMENT_REQUIRED = 402 + FORBIDDEN = 403 + NOT_FOUND = 404 + METHOD_NOT_ALLOWED = 405 + NOT_ACCEPTABLE = 406 + PROXY_AUTHENTICATION_REQUIRED = 407 + REQUEST_TIMEOUT = 408 + CONFLICT = 409 + GONE = 410 + LENGTH_REQUIRED = 411 + PRECONDITION_FAILED = 412 + REQUEST_ENTITY_TOO_LARGE = 413 + REQUEST_URI_TOO_LONG = 414 + UNSUPPORTED_MEDIA_TYPE = 415 + REQUESTED_RANGE_NOT_SATISFIABLE = 416 + EXPECTATION_FAILED = 417 + UNPROCESSABLE_ENTITY = 422 + LOCKED = 423 + FAILED_DEPENDENCY = 424 + UPGRADE_REQUIRED = 426 + PRECONDITION_REQUIRED = 428 + TOO_MANY_REQUESTS = 429 + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 + INTERNAL_SERVER_ERROR = 500 + NOT_IMPLEMENTED = 501 + BAD_GATEWAY = 502 + SERVICE_UNAVAILABLE = 503 + GATEWAY_TIMEOUT = 504 + HTTP_VERSION_NOT_SUPPORTED = 505 + VARIANT_ALSO_NEGOTIATES = 506 + INSUFFICIENT_STORAGE = 507 + LOOP_DETECTED = 508 + NOT_EXTENDED = 510 + NETWORK_AUTHENTICATION_REQUIRED = 511 + MISDIRECTED_REQUEST = 421 + UNAVAILABLE_FOR_LEGAL_REASONS = 451 if sys.version_info >= (3, 9): EARLY_HINTS: Literal[103] IM_A_TEAPOT: Literal[418] @@ -94,12 +94,12 @@ if sys.version_info >= (3, 11): class HTTPMethod(StrEnum): @property def description(self) -> str: ... - CONNECT: str - DELETE: str - GET: str - HEAD: str - OPTIONS: str - PATCH: str - POST: str - PUT: str - TRACE: str + CONNECT = "CONNECT" + DELETE = "DELETE" + GET = "GET" + HEAD = "HEAD" + OPTIONS = "OPTIONS" + PATCH = "PATCH" + POST = "POST" + PUT = "PUT" + TRACE = "TRACE" diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index fb5450730f60..f68d9d0ca7d7 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -3,7 +3,7 @@ import io import ssl import sys import types -from _typeshed import ReadableBuffer, SupportsRead, WriteableBuffer +from _typeshed import ReadableBuffer, SupportsRead, SupportsReadline, WriteableBuffer from collections.abc import Callable, Iterable, Iterator, Mapping from socket import socket from typing import Any, BinaryIO, TypeVar, overload @@ -33,6 +33,7 @@ __all__ = [ _DataType: TypeAlias = SupportsRead[bytes] | Iterable[ReadableBuffer] | ReadableBuffer _T = TypeVar("_T") +_MessageT = TypeVar("_MessageT", bound=email.message.Message) HTTP_PORT: int HTTPS_PORT: int @@ -97,28 +98,13 @@ NETWORK_AUTHENTICATION_REQUIRED: int responses: dict[int, str] -class HTTPMessage(email.message.Message): +class HTTPMessage(email.message.Message[str, str]): def getallmatchingheaders(self, name: str) -> list[str]: ... # undocumented - # override below all of Message's methods that use `_HeaderType` / `_HeaderTypeParam` with `str` - # `HTTPMessage` breaks the Liskov substitution principle by only intending for `str` headers - # This is easier than making `Message` generic - def __getitem__(self, name: str) -> str | None: ... - def __setitem__(self, name: str, val: str) -> None: ... # type: ignore[override] - def values(self) -> list[str]: ... - def items(self) -> list[tuple[str, str]]: ... - @overload - def get(self, name: str, failobj: None = None) -> str | None: ... - @overload - def get(self, name: str, failobj: _T) -> str | _T: ... - @overload - def get_all(self, name: str, failobj: None = None) -> list[str] | None: ... - @overload - def get_all(self, name: str, failobj: _T) -> list[str] | _T: ... - def replace_header(self, _name: str, _value: str) -> None: ... # type: ignore[override] - def set_raw(self, name: str, value: str) -> None: ... # type: ignore[override] - def raw_items(self) -> Iterator[tuple[str, str]]: ... -def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... +@overload +def parse_headers(fp: SupportsReadline[bytes], _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def parse_headers(fp: SupportsReadline[bytes]) -> HTTPMessage: ... class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible method definitions in the base classes msg: HTTPMessage diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index bb5ddc37c603..0abf16d9d0ab 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -26,7 +26,7 @@ from types import ( WrapperDescriptorType, ) from typing import Any, ClassVar, Literal, NamedTuple, Protocol, TypeVar, overload -from typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard +from typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard, TypeIs if sys.version_info >= (3, 11): __all__ = [ @@ -192,10 +192,10 @@ if sys.version_info >= (3, 11): def getmembers_static(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn: ... def getmodulename(path: StrPath) -> str | None: ... -def ismodule(object: object) -> TypeGuard[ModuleType]: ... -def isclass(object: object) -> TypeGuard[type[Any]]: ... -def ismethod(object: object) -> TypeGuard[MethodType]: ... -def isfunction(object: object) -> TypeGuard[FunctionType]: ... +def ismodule(object: object) -> TypeIs[ModuleType]: ... +def isclass(object: object) -> TypeIs[type[Any]]: ... +def ismethod(object: object) -> TypeIs[MethodType]: ... +def isfunction(object: object) -> TypeIs[FunctionType]: ... if sys.version_info >= (3, 12): def markcoroutinefunction(func: _F) -> _F: ... @@ -214,9 +214,9 @@ def iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[ def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ... @overload def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... -def isgenerator(object: object) -> TypeGuard[GeneratorType[Any, Any, Any]]: ... -def iscoroutine(object: object) -> TypeGuard[CoroutineType[Any, Any, Any]]: ... -def isawaitable(object: object) -> TypeGuard[Awaitable[Any]]: ... +def isgenerator(object: object) -> TypeIs[GeneratorType[Any, Any, Any]]: ... +def iscoroutine(object: object) -> TypeIs[CoroutineType[Any, Any, Any]]: ... +def isawaitable(object: object) -> TypeIs[Awaitable[Any]]: ... @overload def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... @overload @@ -230,18 +230,18 @@ class _SupportsSet(Protocol[_T_cont, _V_cont]): class _SupportsDelete(Protocol[_T_cont]): def __delete__(self, instance: _T_cont, /) -> None: ... -def isasyncgen(object: object) -> TypeGuard[AsyncGeneratorType[Any, Any]]: ... -def istraceback(object: object) -> TypeGuard[TracebackType]: ... -def isframe(object: object) -> TypeGuard[FrameType]: ... -def iscode(object: object) -> TypeGuard[CodeType]: ... -def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... +def isasyncgen(object: object) -> TypeIs[AsyncGeneratorType[Any, Any]]: ... +def istraceback(object: object) -> TypeIs[TracebackType]: ... +def isframe(object: object) -> TypeIs[FrameType]: ... +def iscode(object: object) -> TypeIs[CodeType]: ... +def isbuiltin(object: object) -> TypeIs[BuiltinFunctionType]: ... if sys.version_info >= (3, 11): - def ismethodwrapper(object: object) -> TypeGuard[MethodWrapperType]: ... + def ismethodwrapper(object: object) -> TypeIs[MethodWrapperType]: ... def isroutine( object: object, -) -> TypeGuard[ +) -> TypeIs[ FunctionType | LambdaType | MethodType @@ -251,11 +251,11 @@ def isroutine( | MethodDescriptorType | ClassMethodDescriptorType ]: ... -def ismethoddescriptor(object: object) -> TypeGuard[MethodDescriptorType]: ... -def ismemberdescriptor(object: object) -> TypeGuard[MemberDescriptorType]: ... +def ismethoddescriptor(object: object) -> TypeIs[MethodDescriptorType]: ... +def ismemberdescriptor(object: object) -> TypeIs[MemberDescriptorType]: ... def isabstract(object: object) -> bool: ... -def isgetsetdescriptor(object: object) -> TypeGuard[GetSetDescriptorType]: ... -def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: ... +def isgetsetdescriptor(object: object) -> TypeIs[GetSetDescriptorType]: ... +def isdatadescriptor(object: object) -> TypeIs[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: ... # # Retrieving source code @@ -347,11 +347,11 @@ if sys.version_info >= (3, 10): # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): - POSITIONAL_ONLY: int - POSITIONAL_OR_KEYWORD: int - VAR_POSITIONAL: int - KEYWORD_ONLY: int - VAR_KEYWORD: int + POSITIONAL_ONLY = 0 + POSITIONAL_OR_KEYWORD = 1 + VAR_POSITIONAL = 2 + KEYWORD_ONLY = 3 + VAR_KEYWORD = 4 @property def description(self) -> str: ... @@ -611,22 +611,22 @@ if sys.version_info >= (3, 9): if sys.version_info >= (3, 12): class BufferFlags(enum.IntFlag): - SIMPLE: int - WRITABLE: int - FORMAT: int - ND: int - STRIDES: int - C_CONTIGUOUS: int - F_CONTIGUOUS: int - ANY_CONTIGUOUS: int - INDIRECT: int - CONTIG: int - CONTIG_RO: int - STRIDED: int - STRIDED_RO: int - RECORDS: int - RECORDS_RO: int - FULL: int - FULL_RO: int - READ: int - WRITE: int + SIMPLE = 0 + WRITABLE = 1 + FORMAT = 4 + ND = 8 + STRIDES = 24 + C_CONTIGUOUS = 56 + F_CONTIGUOUS = 88 + ANY_CONTIGUOUS = 152 + INDIRECT = 280 + CONTIG = 9 + CONTIG_RO = 8 + STRIDED = 25 + STRIDED_RO = 24 + RECORDS = 29 + RECORDS_RO = 28 + FULL = 285 + FULL_RO = 284 + READ = 256 + WRITE = 512 diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index a62d0674df4c..f5f7f91ece61 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -597,7 +597,7 @@ class StreamHandler(Handler, Generic[_StreamT]): @overload def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ... @overload - def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... + def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 def setStream(self, stream: _StreamT) -> _StreamT | None: ... if sys.version_info >= (3, 11): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index a3edaa463818..9a45a81559c0 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -1,13 +1,13 @@ import ctypes import sys from collections.abc import Callable, Iterable, Sequence -from ctypes import _CData +from ctypes import _CData, _SimpleCData, c_char from logging import Logger, _Level as _LoggingLevel from multiprocessing import popen_fork, popen_forkserver, popen_spawn_posix, popen_spawn_win32, queues, synchronize from multiprocessing.managers import SyncManager from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess -from multiprocessing.sharedctypes import Synchronized, SynchronizedArray +from multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString from typing import Any, ClassVar, Literal, TypeVar, overload from typing_extensions import TypeAlias @@ -19,6 +19,7 @@ else: __all__ = () _LockLike: TypeAlias = synchronize.Lock | synchronize.RLock +_T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) class ProcessError(Exception): ... @@ -79,6 +80,10 @@ class BaseContext: @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload + def Value( + self, typecode_or_type: type[_SimpleCData[_T]], *args: Any, lock: Literal[True] | _LockLike = True + ) -> Synchronized[_T]: ... + @overload def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> Synchronized[_CT]: ... @overload def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[_CT]: ... @@ -87,6 +92,10 @@ class BaseContext: @overload def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ... @overload + def Array( + self, typecode_or_type: type[c_char], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True + ) -> SynchronizedString: ... + @overload def Array( self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] ) -> SynchronizedArray[_CT]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index 048c6fe8d891..b417925fb17b 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -14,7 +14,7 @@ class Barrier(threading.Barrier): self, parties: int, action: Callable[[], object] | None = None, timeout: float | None = None, *ctx: BaseContext ) -> None: ... -class Condition(AbstractContextManager[bool]): +class Condition(AbstractContextManager[bool, None]): def __init__(self, lock: _LockLike | None = None, *, ctx: BaseContext) -> None: ... def notify(self, n: int = 1) -> None: ... def notify_all(self) -> None: ... @@ -34,7 +34,7 @@ class Event: def wait(self, timeout: float | None = None) -> bool: ... # Not part of public API -class SemLock(AbstractContextManager[bool]): +class SemLock(AbstractContextManager[bool, None]): def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... def __exit__( diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 89d906d4edfc..e1c7855c0bb6 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -747,7 +747,7 @@ if sys.platform != "win32": def getcwd() -> str: ... def getcwdb() -> bytes: ... -def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None: ... +def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = ...) -> None: ... if sys.platform != "win32" and sys.platform != "linux": def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = True) -> None: ... # some flavors of Unix @@ -794,7 +794,7 @@ def replace( ) -> None: ... def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... -class _ScandirIterator(Iterator[DirEntry[AnyStr]], AbstractContextManager[_ScandirIterator[AnyStr]]): +class _ScandirIterator(Iterator[DirEntry[AnyStr]], AbstractContextManager[_ScandirIterator[AnyStr], None]): def __next__(self) -> DirEntry[AnyStr]: ... def __exit__(self, *args: Unused) -> None: ... def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index f7912a784987..09637673ce21 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -11,8 +11,8 @@ if sys.version_info < (3, 9): __all__ += ["readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes", "Data"] class PlistFormat(Enum): - FMT_XML: int - FMT_BINARY: int + FMT_XML = 1 + FMT_BINARY = 2 FMT_XML = PlistFormat.FMT_XML FMT_BINARY = PlistFormat.FMT_BINARY diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index d1571fd94be5..83256b433035 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -14,15 +14,15 @@ else: _Selector: TypeAlias = str | float | int class SortKey(StrEnum): - CALLS: str - CUMULATIVE: str - FILENAME: str - LINE: str - NAME: str - NFL: str - PCALLS: str - STDNAME: str - TIME: str + CALLS = "calls" + CUMULATIVE = "cumulative" + FILENAME = "filename" + LINE = "line" + NAME = "name" + NFL = "nfl" + PCALLS = "pcalls" + STDNAME = "stdname" + TIME = "time" if sys.version_info >= (3, 9): from dataclasses import dataclass diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 81561a202883..334ce79b5dd0 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -12,9 +12,9 @@ class PyCompileError(Exception): def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = "") -> None: ... class PycInvalidationMode(enum.Enum): - TIMESTAMP: int - CHECKED_HASH: int - UNCHECKED_HASH: int + TIMESTAMP = 1 + CHECKED_HASH = 2 + UNCHECKED_HASH = 3 def _get_default_invalidation_mode() -> PycInvalidationMode: ... def compile( diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 663ee2fe7430..cbb7440b9147 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -9,57 +9,57 @@ from typing_extensions import Never, TypeAlias NSIG: int class Signals(IntEnum): - SIGABRT: int - SIGFPE: int - SIGILL: int - SIGINT: int - SIGSEGV: int - SIGTERM: int + SIGABRT = 6 + SIGFPE = 8 + SIGILL = 4 + SIGINT = 2 + SIGSEGV = 11 + SIGTERM = 15 if sys.platform == "win32": - SIGBREAK: int - CTRL_C_EVENT: int - CTRL_BREAK_EVENT: int + SIGBREAK = 21 + CTRL_C_EVENT = 0 + CTRL_BREAK_EVENT = 1 else: - SIGALRM: int - SIGBUS: int - SIGCHLD: int - SIGCONT: int - SIGHUP: int - SIGIO: int - SIGIOT: int - SIGKILL: int - SIGPIPE: int - SIGPROF: int - SIGQUIT: int - SIGSTOP: int - SIGSYS: int - SIGTRAP: int - SIGTSTP: int - SIGTTIN: int - SIGTTOU: int - SIGURG: int - SIGUSR1: int - SIGUSR2: int - SIGVTALRM: int - SIGWINCH: int - SIGXCPU: int - SIGXFSZ: int + SIGALRM = 14 + SIGBUS = 7 + SIGCHLD = 17 + SIGCONT = 18 + SIGHUP = 1 + SIGIO = 29 + SIGIOT = 6 + SIGKILL = 9 + SIGPIPE = 13 + SIGPROF = 27 + SIGQUIT = 3 + SIGSTOP = 19 + SIGSYS = 31 + SIGTRAP = 5 + SIGTSTP = 20 + SIGTTIN = 21 + SIGTTOU = 22 + SIGURG = 23 + SIGUSR1 = 10 + SIGUSR2 = 12 + SIGVTALRM = 26 + SIGWINCH = 28 + SIGXCPU = 24 + SIGXFSZ = 25 if sys.platform != "linux": - SIGEMT: int - SIGINFO: int + SIGEMT = 7 + SIGINFO = 29 if sys.platform != "darwin": - SIGCLD: int - SIGPOLL: int - SIGPWR: int - SIGRTMAX: int - SIGRTMIN: int + SIGCLD = 17 + SIGPOLL = 29 + SIGPWR = 30 + SIGRTMAX = 64 + SIGRTMIN = 34 if sys.version_info >= (3, 11): - SIGSTKFLT: int + SIGSTKFLT = 16 class Handlers(IntEnum): - SIG_DFL: int - SIG_IGN: int + SIG_DFL = 0 + SIG_IGN = 1 SIG_DFL: Handlers SIG_IGN: Handlers @@ -123,9 +123,9 @@ else: ITIMER_VIRTUAL: int class Sigmasks(IntEnum): - SIG_BLOCK: int - SIG_UNBLOCK: int - SIG_SETMASK: int + SIG_BLOCK = 0 + SIG_UNBLOCK = 1 + SIG_SETMASK = 2 SIG_BLOCK = Sigmasks.SIG_BLOCK SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index cdbd70533714..a309bac9370a 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -480,51 +480,51 @@ EAGAIN: int EWOULDBLOCK: int class AddressFamily(IntEnum): - AF_INET: int - AF_INET6: int - AF_APPLETALK: int - AF_DECnet: int - AF_IPX: int - AF_SNA: int - AF_UNSPEC: int + AF_INET = 2 + AF_INET6 = 10 + AF_APPLETALK = 5 + AF_DECnet = ... + AF_IPX = 4 + AF_SNA = 22 + AF_UNSPEC = 0 if sys.platform != "darwin": - AF_IRDA: int + AF_IRDA = 23 if sys.platform != "win32": - AF_ROUTE: int - AF_SYSTEM: int - AF_UNIX: int + AF_ROUTE = 16 + AF_SYSTEM = 32 + AF_UNIX = 1 if sys.platform != "win32" and sys.platform != "darwin": - AF_AAL5: int - AF_ASH: int - AF_ATMPVC: int - AF_ATMSVC: int - AF_AX25: int - AF_BRIDGE: int - AF_ECONET: int - AF_KEY: int - AF_LLC: int - AF_NETBEUI: int - AF_NETROM: int - AF_PPPOX: int - AF_ROSE: int - AF_SECURITY: int - AF_WANPIPE: int - AF_X25: int + AF_AAL5 = ... + AF_ASH = 18 + AF_ATMPVC = 8 + AF_ATMSVC = 20 + AF_AX25 = 3 + AF_BRIDGE = 7 + AF_ECONET = 19 + AF_KEY = 15 + AF_LLC = 26 + AF_NETBEUI = 13 + AF_NETROM = 6 + AF_PPPOX = 24 + AF_ROSE = 11 + AF_SECURITY = 14 + AF_WANPIPE = 25 + AF_X25 = 9 if sys.platform == "linux": - AF_CAN: int - AF_PACKET: int - AF_RDS: int - AF_TIPC: int - AF_ALG: int - AF_NETLINK: int - AF_VSOCK: int - AF_QIPCRTR: int + AF_CAN = 29 + AF_PACKET = 17 + AF_RDS = 21 + AF_TIPC = 30 + AF_ALG = 38 + AF_NETLINK = 16 + AF_VSOCK = 40 + AF_QIPCRTR = 42 if sys.platform != "win32" or sys.version_info >= (3, 9): - AF_LINK: int + AF_LINK = 33 if sys.platform != "darwin": - AF_BLUETOOTH: int + AF_BLUETOOTH = 32 if sys.platform == "win32" and sys.version_info >= (3, 12): - AF_HYPERV: int + AF_HYPERV = 34 AF_INET = AddressFamily.AF_INET AF_INET6 = AddressFamily.AF_INET6 @@ -579,14 +579,14 @@ if sys.platform == "win32" and sys.version_info >= (3, 12): AF_HYPERV = AddressFamily.AF_HYPERV class SocketKind(IntEnum): - SOCK_STREAM: int - SOCK_DGRAM: int - SOCK_RAW: int - SOCK_RDM: int - SOCK_SEQPACKET: int + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 + SOCK_RDM = 4 + SOCK_SEQPACKET = 5 if sys.platform == "linux": - SOCK_CLOEXEC: int - SOCK_NONBLOCK: int + SOCK_CLOEXEC = 524288 + SOCK_NONBLOCK = 2048 SOCK_STREAM = SocketKind.SOCK_STREAM SOCK_DGRAM = SocketKind.SOCK_DGRAM @@ -598,32 +598,32 @@ if sys.platform == "linux": SOCK_NONBLOCK = SocketKind.SOCK_NONBLOCK class MsgFlag(IntFlag): - MSG_CTRUNC: int - MSG_DONTROUTE: int - MSG_OOB: int - MSG_PEEK: int - MSG_TRUNC: int - MSG_WAITALL: int + MSG_CTRUNC = 8 + MSG_DONTROUTE = 4 + MSG_OOB = 1 + MSG_PEEK = 2 + MSG_TRUNC = 32 + MSG_WAITALL = 256 if sys.platform != "darwin": - MSG_BCAST: int - MSG_MCAST: int - MSG_ERRQUEUE: int + MSG_BCAST = 1024 + MSG_MCAST = 2048 + MSG_ERRQUEUE = 8192 if sys.platform != "win32" and sys.platform != "darwin": - MSG_BTAG: int - MSG_CMSG_CLOEXEC: int - MSG_CONFIRM: int - MSG_ETAG: int - MSG_FASTOPEN: int - MSG_MORE: int - MSG_NOTIFICATION: int + MSG_BTAG = ... + MSG_CMSG_CLOEXEC = 1073741821 + MSG_CONFIRM = 2048 + MSG_ETAG = ... + MSG_FASTOPEN = 536870912 + MSG_MORE = 32768 + MSG_NOTIFICATION = ... if sys.platform != "win32": - MSG_DONTWAIT: int - MSG_EOF: int - MSG_EOR: int - MSG_NOSIGNAL: int # sometimes this exists on darwin, sometimes not + MSG_DONTWAIT = 64 + MSG_EOF = 256 + MSG_EOR = 128 + MSG_NOSIGNAL = 16384 # sometimes this exists on darwin, sometimes not MSG_CTRUNC = MsgFlag.MSG_CTRUNC MSG_DONTROUTE = MsgFlag.MSG_DONTROUTE @@ -653,17 +653,17 @@ if sys.platform != "win32" and sys.platform != "darwin": MSG_NOTIFICATION = MsgFlag.MSG_NOTIFICATION class AddressInfo(IntFlag): - AI_ADDRCONFIG: int - AI_ALL: int - AI_CANONNAME: int - AI_NUMERICHOST: int - AI_NUMERICSERV: int - AI_PASSIVE: int - AI_V4MAPPED: int + AI_ADDRCONFIG = 32 + AI_ALL = 16 + AI_CANONNAME = 2 + AI_NUMERICHOST = 4 + AI_NUMERICSERV = 1024 + AI_PASSIVE = 1 + AI_V4MAPPED = 8 if sys.platform != "win32": - AI_DEFAULT: int - AI_MASK: int - AI_V4MAPPED_CFG: int + AI_DEFAULT = 1536 + AI_MASK = 5127 + AI_V4MAPPED_CFG = 512 AI_ADDRCONFIG = AddressInfo.AI_ADDRCONFIG AI_ALL = AddressInfo.AI_ALL diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 15d86372531a..81c68c69ec4e 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -138,23 +138,23 @@ if sys.platform == "win32": def enum_crls(store_name: str) -> _EnumRetType: ... class VerifyMode(enum.IntEnum): - CERT_NONE: int - CERT_OPTIONAL: int - CERT_REQUIRED: int + CERT_NONE = 0 + CERT_OPTIONAL = 1 + CERT_REQUIRED = 2 CERT_NONE: VerifyMode CERT_OPTIONAL: VerifyMode CERT_REQUIRED: VerifyMode class VerifyFlags(enum.IntFlag): - VERIFY_DEFAULT: int - VERIFY_CRL_CHECK_LEAF: int - VERIFY_CRL_CHECK_CHAIN: int - VERIFY_X509_STRICT: int - VERIFY_X509_TRUSTED_FIRST: int + VERIFY_DEFAULT = 0 + VERIFY_CRL_CHECK_LEAF = 4 + VERIFY_CRL_CHECK_CHAIN = 12 + VERIFY_X509_STRICT = 32 + VERIFY_X509_TRUSTED_FIRST = 32768 if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS: int - VERIFY_X509_PARTIAL_CHAIN: int + VERIFY_ALLOW_PROXY_CERTS = 64 + VERIFY_X509_PARTIAL_CHAIN = 524288 VERIFY_DEFAULT: VerifyFlags VERIFY_CRL_CHECK_LEAF: VerifyFlags @@ -167,15 +167,15 @@ if sys.version_info >= (3, 10): VERIFY_X509_PARTIAL_CHAIN: VerifyFlags class _SSLMethod(enum.IntEnum): - PROTOCOL_SSLv23: int - PROTOCOL_SSLv2: int - PROTOCOL_SSLv3: int - PROTOCOL_TLSv1: int - PROTOCOL_TLSv1_1: int - PROTOCOL_TLSv1_2: int - PROTOCOL_TLS: int - PROTOCOL_TLS_CLIENT: int - PROTOCOL_TLS_SERVER: int + PROTOCOL_SSLv23 = 2 + PROTOCOL_SSLv2 = ... + PROTOCOL_SSLv3 = ... + PROTOCOL_TLSv1 = 3 + PROTOCOL_TLSv1_1 = 4 + PROTOCOL_TLSv1_2 = 5 + PROTOCOL_TLS = 2 + PROTOCOL_TLS_CLIENT = 16 + PROTOCOL_TLS_SERVER = 17 PROTOCOL_SSLv23: _SSLMethod PROTOCOL_SSLv2: _SSLMethod @@ -188,25 +188,25 @@ PROTOCOL_TLS_CLIENT: _SSLMethod PROTOCOL_TLS_SERVER: _SSLMethod class Options(enum.IntFlag): - OP_ALL: int - OP_NO_SSLv2: int - OP_NO_SSLv3: int - OP_NO_TLSv1: int - OP_NO_TLSv1_1: int - OP_NO_TLSv1_2: int - OP_NO_TLSv1_3: int - OP_CIPHER_SERVER_PREFERENCE: int - OP_SINGLE_DH_USE: int - OP_SINGLE_ECDH_USE: int - OP_NO_COMPRESSION: int - OP_NO_TICKET: int - OP_NO_RENEGOTIATION: int - OP_ENABLE_MIDDLEBOX_COMPAT: int + OP_ALL = 2147483728 + OP_NO_SSLv2 = 0 + OP_NO_SSLv3 = 33554432 + OP_NO_TLSv1 = 67108864 + OP_NO_TLSv1_1 = 268435456 + OP_NO_TLSv1_2 = 134217728 + OP_NO_TLSv1_3 = 536870912 + OP_CIPHER_SERVER_PREFERENCE = 4194304 + OP_SINGLE_DH_USE = 0 + OP_SINGLE_ECDH_USE = 0 + OP_NO_COMPRESSION = 131072 + OP_NO_TICKET = 16384 + OP_NO_RENEGOTIATION = 1073741824 + OP_ENABLE_MIDDLEBOX_COMPAT = 1048576 if sys.version_info >= (3, 12): - OP_LEGACY_SERVER_CONNECT: int - OP_ENABLE_KTLS: int + OP_LEGACY_SERVER_CONNECT = 4 + OP_ENABLE_KTLS = 8 if sys.version_info >= (3, 11) or sys.platform == "linux": - OP_IGNORE_UNEXPECTED_EOF: int + OP_IGNORE_UNEXPECTED_EOF = 128 OP_ALL: Options OP_NO_SSLv2: Options @@ -246,33 +246,33 @@ OPENSSL_VERSION_INFO: tuple[int, int, int, int, int] OPENSSL_VERSION_NUMBER: int class AlertDescription(enum.IntEnum): - ALERT_DESCRIPTION_ACCESS_DENIED: int - ALERT_DESCRIPTION_BAD_CERTIFICATE: int - ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int - ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int - ALERT_DESCRIPTION_BAD_RECORD_MAC: int - ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int - ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int - ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int - ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int - ALERT_DESCRIPTION_CLOSE_NOTIFY: int - ALERT_DESCRIPTION_DECODE_ERROR: int - ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int - ALERT_DESCRIPTION_DECRYPT_ERROR: int - ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int - ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int - ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int - ALERT_DESCRIPTION_INTERNAL_ERROR: int - ALERT_DESCRIPTION_NO_RENEGOTIATION: int - ALERT_DESCRIPTION_PROTOCOL_VERSION: int - ALERT_DESCRIPTION_RECORD_OVERFLOW: int - ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int - ALERT_DESCRIPTION_UNKNOWN_CA: int - ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int - ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int - ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int - ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int - ALERT_DESCRIPTION_USER_CANCELLED: int + ALERT_DESCRIPTION_ACCESS_DENIED = 49 + ALERT_DESCRIPTION_BAD_CERTIFICATE = 42 + ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = 114 + ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = 113 + ALERT_DESCRIPTION_BAD_RECORD_MAC = 20 + ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = 45 + ALERT_DESCRIPTION_CERTIFICATE_REVOKED = 44 + ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = 46 + ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = 111 + ALERT_DESCRIPTION_CLOSE_NOTIFY = 0 + ALERT_DESCRIPTION_DECODE_ERROR = 50 + ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = 30 + ALERT_DESCRIPTION_DECRYPT_ERROR = 51 + ALERT_DESCRIPTION_HANDSHAKE_FAILURE = 40 + ALERT_DESCRIPTION_ILLEGAL_PARAMETER = 47 + ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = 71 + ALERT_DESCRIPTION_INTERNAL_ERROR = 80 + ALERT_DESCRIPTION_NO_RENEGOTIATION = 100 + ALERT_DESCRIPTION_PROTOCOL_VERSION = 70 + ALERT_DESCRIPTION_RECORD_OVERFLOW = 22 + ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = 10 + ALERT_DESCRIPTION_UNKNOWN_CA = 48 + ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = 115 + ALERT_DESCRIPTION_UNRECOGNIZED_NAME = 112 + ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = 43 + ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = 110 + ALERT_DESCRIPTION_USER_CANCELLED = 90 ALERT_DESCRIPTION_HANDSHAKE_FAILURE: AlertDescription ALERT_DESCRIPTION_INTERNAL_ERROR: AlertDescription @@ -316,8 +316,8 @@ class _ASN1Object(_ASN1ObjectBase): def fromname(cls, name: str) -> Self: ... class Purpose(_ASN1Object, enum.Enum): - SERVER_AUTH: _ASN1Object - CLIENT_AUTH: _ASN1Object + SERVER_AUTH = (129, "serverAuth", "TLS Web Server Authentication", "1.3.6.1.5.5.7.3.2") # pyright: ignore[reportCallIssue] + CLIENT_AUTH = (130, "clientAuth", "TLS Web Client Authentication", "1.3.6.1.5.5.7.3.1") # pyright: ignore[reportCallIssue] class SSLSocket(socket.socket): context: SSLContext @@ -371,13 +371,13 @@ class SSLSocket(socket.socket): def get_unverified_chain(self) -> list[bytes]: ... class TLSVersion(enum.IntEnum): - MINIMUM_SUPPORTED: int - MAXIMUM_SUPPORTED: int - SSLv3: int - TLSv1: int - TLSv1_1: int - TLSv1_2: int - TLSv1_3: int + MINIMUM_SUPPORTED = -2 + MAXIMUM_SUPPORTED = -1 + SSLv3 = 768 + TLSv1 = 769 + TLSv1_1 = 770 + TLSv1_2 = 771 + TLSv1_3 = 772 class SSLContext: check_hostname: bool @@ -506,15 +506,15 @@ class SSLSession: def __eq__(self, value: object, /) -> bool: ... class SSLErrorNumber(enum.IntEnum): - SSL_ERROR_EOF: int - SSL_ERROR_INVALID_ERROR_CODE: int - SSL_ERROR_SSL: int - SSL_ERROR_SYSCALL: int - SSL_ERROR_WANT_CONNECT: int - SSL_ERROR_WANT_READ: int - SSL_ERROR_WANT_WRITE: int - SSL_ERROR_WANT_X509_LOOKUP: int - SSL_ERROR_ZERO_RETURN: int + SSL_ERROR_EOF = 8 + SSL_ERROR_INVALID_ERROR_CODE = 10 + SSL_ERROR_SSL = 1 + SSL_ERROR_SYSCALL = 5 + SSL_ERROR_WANT_CONNECT = 7 + SSL_ERROR_WANT_READ = 2 + SSL_ERROR_WANT_WRITE = 3 + SSL_ERROR_WANT_X509_LOOKUP = 4 + SSL_ERROR_ZERO_RETURN = 6 SSL_ERROR_EOF: SSLErrorNumber # undocumented SSL_ERROR_INVALID_ERROR_CODE: SSLErrorNumber # undocumented diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 80bc56ef53f3..d8ce17535eab 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -194,45 +194,45 @@ if sys.version_info >= (3, 11): serial: int class EventType(StrEnum): - Activate: str - ButtonPress: str + Activate = "36" + ButtonPress = "4" Button = ButtonPress - ButtonRelease: str - Circulate: str - CirculateRequest: str - ClientMessage: str - Colormap: str - Configure: str - ConfigureRequest: str - Create: str - Deactivate: str - Destroy: str - Enter: str - Expose: str - FocusIn: str - FocusOut: str - GraphicsExpose: str - Gravity: str - KeyPress: str - Key = KeyPress - KeyRelease: str - Keymap: str - Leave: str - Map: str - MapRequest: str - Mapping: str - Motion: str - MouseWheel: str - NoExpose: str - Property: str - Reparent: str - ResizeRequest: str - Selection: str - SelectionClear: str - SelectionRequest: str - Unmap: str - VirtualEvent: str - Visibility: str + ButtonRelease = "5" + Circulate = "26" + CirculateRequest = "27" + ClientMessage = "33" + Colormap = "32" + Configure = "22" + ConfigureRequest = "23" + Create = "16" + Deactivate = "37" + Destroy = "17" + Enter = "7" + Expose = "12" + FocusIn = "9" + FocusOut = "10" + GraphicsExpose = "13" + Gravity = "24" + KeyPress = "2" + Key = "2" + KeyRelease = "3" + Keymap = "11" + Leave = "8" + Map = "19" + MapRequest = "20" + Mapping = "34" + Motion = "6" + MouseWheel = "38" + NoExpose = "14" + Property = "28" + Reparent = "21" + ResizeRequest = "25" + Selection = "31" + SelectionClear = "29" + SelectionRequest = "30" + Unmap = "18" + VirtualEvent = "35" + Visibility = "15" _W = TypeVar("_W", bound=Misc) # Events considered covariant because you should never assign to event.widget. diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 580322b653b4..4b80397bdd7a 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -129,12 +129,6 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 12): __all__ += ["TypeAliasType", "override"] -ContextManager = AbstractContextManager -AsyncContextManager = AbstractAsyncContextManager - -# This itself is only available during type checking -def type_check_only(func_or_cls: _F) -> _F: ... - Any = object() def final(f: _T) -> _T: ... @@ -183,12 +177,6 @@ class _SpecialForm: def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... -_F = TypeVar("_F", bound=Callable[..., Any]) -_P = _ParamSpec("_P") -_T = TypeVar("_T") - -def overload(func: _F) -> _F: ... - Union: _SpecialForm Generic: _SpecialForm # Protocol is only present in 3.8 and later, but mypy needs it unconditionally @@ -295,6 +283,10 @@ if sys.version_info >= (3, 10): else: def NewType(name: str, tp: Any) -> Any: ... +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = _ParamSpec("_P") +_T = TypeVar("_T") + # These type variables are used by the container types. _S = TypeVar("_S") _KT = TypeVar("_KT") # Key type. @@ -304,9 +296,13 @@ _KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. _TC = TypeVar("_TC", bound=type[object]) +def overload(func: _F) -> _F: ... def no_type_check(arg: _F) -> _F: ... def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... +# This itself is only available during type checking +def type_check_only(func_or_cls: _F) -> _F: ... + # Type aliases and type constructors class _Alias: @@ -432,10 +428,22 @@ class Generator(Iterator[_YieldT_co], Generic[_YieldT_co, _SendT_contra, _Return @property def gi_yieldfrom(self) -> Generator[Any, Any, Any] | None: ... +# NOTE: Technically we would like this to be able to accept a second parameter as well, just +# like it's counterpart in contextlib, however `typing._SpecialGenericAlias` enforces the +# correct number of arguments at runtime, so we would be hiding runtime errors. +@runtime_checkable +class ContextManager(AbstractContextManager[_T_co, bool | None], Protocol[_T_co]): ... + +# NOTE: Technically we would like this to be able to accept a second parameter as well, just +# like it's counterpart in contextlib, however `typing._SpecialGenericAlias` enforces the +# correct number of arguments at runtime, so we would be hiding runtime errors. +@runtime_checkable +class AsyncContextManager(AbstractAsyncContextManager[_T_co, bool | None], Protocol[_T_co]): ... + @runtime_checkable class Awaitable(Protocol[_T_co]): @abstractmethod - def __await__(self) -> Generator[Any, None, _T_co]: ... + def __await__(self) -> Generator[Any, Any, _T_co]: ... class Coroutine(Awaitable[_ReturnT_co], Generic[_YieldT_co, _SendT_contra, _ReturnT_co]): __name__: str @@ -445,7 +453,7 @@ class Coroutine(Awaitable[_ReturnT_co], Generic[_YieldT_co, _SendT_contra, _Retu @property def cr_code(self) -> CodeType: ... @property - def cr_frame(self) -> FrameType: ... + def cr_frame(self) -> FrameType | None: ... @property def cr_running(self) -> bool: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 6e64e7a85560..dd61b83a658a 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -188,7 +188,7 @@ class _patch(Generic[_T]): # but that's impossible with the current type system. if sys.version_info >= (3, 10): def __init__( - self: _patch[_T], + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 getter: Callable[[], Any], attribute: str, new: _T, @@ -203,7 +203,7 @@ class _patch(Generic[_T]): ) -> None: ... else: def __init__( - self: _patch[_T], + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 getter: Callable[[], Any], attribute: str, new: _T, diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index e1ea424f9680..1be7a5ef009f 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -7,9 +7,9 @@ from typing_extensions import TypeAlias _FieldsType: TypeAlias = tuple[int, int, int, int, int, int] class SafeUUID(Enum): - safe: int - unsafe: int - unknown: None + safe = 0 + unsafe = -1 + unknown = None class UUID: def __init__( diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 8f3ad0631c10..e345124237da 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -51,10 +51,17 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self: WeakValueDictionary[_KT, _VT], other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], /) -> None: ... + def __init__( + self: WeakValueDictionary[_KT, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], + /, + ) -> None: ... @overload def __init__( - self: WeakValueDictionary[str, _VT], other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (), /, **kwargs: _VT + self: WeakValueDictionary[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (), + /, + **kwargs: _VT, ) -> None: ... def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ...