diff --git a/mypy/stubgenc.py b/mypy/stubgenc.py index c673ea929dfa..b03a88cf6f43 100755 --- a/mypy/stubgenc.py +++ b/mypy/stubgenc.py @@ -765,7 +765,7 @@ def generate_property_stub( def get_type_fullname(self, typ: type) -> str: """Given a type, return a string representation""" - if typ is Any: # type: ignore[comparison-overlap] + if typ is Any: return "Any" typename = getattr(typ, "__qualname__", typ.__name__) module_name = self.get_obj_module(typ) diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 2b56a4e97519..99d21b67360a 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -3,6 +3,7 @@ # See the README.md file in this directory for more information. import sys +import typing_extensions from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as AbstractSet, Sized from dataclasses import Field from os import PathLike @@ -328,9 +329,9 @@ class structseq(Generic[_T_co]): # The second parameter will accept a dict of any kind without raising an exception, # but only has any meaning if you supply it a dict where the keys are strings. # https://github.com/python/typeshed/pull/6560#discussion_r767149830 - def __new__(cls: type[Self], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> Self: ... + def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> typing_extensions.Self: ... if sys.version_info >= (3, 13): - def __replace__(self: Self, **kwargs: Any) -> Self: ... + def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... # Superset of typing.AnyStr that also includes LiteralString AnyOrLiteralStr = TypeVar("AnyOrLiteralStr", str, bytes, LiteralString) # noqa: Y001 diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index ded1933dd659..ab102f124c2e 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -76,7 +76,7 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]: ... @property def _protocol_paused(self) -> bool: ... - def write(self, data: bytes | bytearray | memoryview) -> None: ... + def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ... # any memoryview format or shape def can_write_eof(self) -> Literal[False]: ... if sys.version_info >= (3, 11): def get_write_buffer_limits(self) -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi index c28ae234f2cc..bce54897f18f 100644 --- a/mypy/typeshed/stdlib/asyncio/transports.pyi +++ b/mypy/typeshed/stdlib/asyncio/transports.pyi @@ -24,8 +24,10 @@ class WriteTransport(BaseTransport): def set_write_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ... def get_write_buffer_size(self) -> int: ... def get_write_buffer_limits(self) -> tuple[int, int]: ... - def write(self, data: bytes | bytearray | memoryview) -> None: ... - def writelines(self, list_of_data: Iterable[bytes | bytearray | memoryview]) -> None: ... + def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ... # any memoryview format or shape + def writelines( + self, list_of_data: Iterable[bytes | bytearray | memoryview[Any]] + ) -> None: ... # any memoryview format or shape def write_eof(self) -> None: ... def can_write_eof(self) -> bool: ... def abort(self) -> None: ... diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index 7a3aa8b442a5..220c41f303fb 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -1,6 +1,6 @@ from _heapq import * from _typeshed import SupportsRichComparison -from collections.abc import Callable, Iterable +from collections.abc import Callable, Generator, Iterable from typing import Any, Final, TypeVar __all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"] @@ -11,7 +11,7 @@ __about__: Final[str] def merge( *iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None, reverse: bool = False -) -> Iterable[_S]: ... +) -> Generator[_S]: ... def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ... def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ... def _heapify_max(heap: list[Any], /) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index b273e19c10cd..1a6fde6000d9 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -6,6 +6,7 @@ import sys from _typeshed import StrPath, SupportsRead, SupportsWrite from collections.abc import Mapping, Sequence from typing import Any, AnyStr, BinaryIO, ClassVar +from typing_extensions import deprecated __all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler"] @@ -72,7 +73,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def guess_type(self, path: StrPath) -> str: ... # undocumented def executable(path: StrPath) -> bool: ... # undocumented - +@deprecated("Deprecated in Python 3.13; removal scheduled for Python 3.15") class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): cgi_directories: list[str] have_fork: bool # undocumented diff --git a/mypy/typeshed/stdlib/importlib/resources/__init__.pyi b/mypy/typeshed/stdlib/importlib/resources/__init__.pyi index f82df8c591fa..a30e6cdce5c6 100644 --- a/mypy/typeshed/stdlib/importlib/resources/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/__init__.pyi @@ -4,7 +4,7 @@ from collections.abc import Iterator from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType -from typing import Any, BinaryIO, TextIO +from typing import Any, BinaryIO, Literal, TextIO from typing_extensions import TypeAlias if sys.version_info >= (3, 11): @@ -51,14 +51,14 @@ else: def open_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> TextIO: ... def read_binary(package: Package, resource: Resource) -> bytes: ... def read_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> str: ... - def path(package: Package, resource: Resource) -> AbstractContextManager[Path]: ... + def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: ... def is_resource(package: Package, name: str) -> bool: ... def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 11): from importlib.resources._common import as_file as as_file elif sys.version_info >= (3, 9): - def as_file(path: Traversable) -> AbstractContextManager[Path]: ... + def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... if sys.version_info >= (3, 11): from importlib.resources._common import files as files diff --git a/mypy/typeshed/stdlib/importlib/resources/_common.pyi b/mypy/typeshed/stdlib/importlib/resources/_common.pyi index f1056f62ed6e..d6a9436544dc 100644 --- a/mypy/typeshed/stdlib/importlib/resources/_common.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/_common.pyi @@ -7,7 +7,7 @@ if sys.version_info >= (3, 11): from contextlib import AbstractContextManager from importlib.abc import ResourceReader, Traversable from pathlib import Path - from typing import overload + from typing import Literal, overload from typing_extensions import TypeAlias, deprecated Package: TypeAlias = str | types.ModuleType @@ -39,4 +39,4 @@ if sys.version_info >= (3, 11): def get_package(package: Package) -> types.ModuleType: ... def from_package(package: types.ModuleType) -> Traversable: ... - def as_file(path: Traversable) -> AbstractContextManager[Path]: ... + def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... diff --git a/mypy/typeshed/stdlib/importlib/resources/_functional.pyi b/mypy/typeshed/stdlib/importlib/resources/_functional.pyi index 97e46bdf0a53..50f3405f9a00 100644 --- a/mypy/typeshed/stdlib/importlib/resources/_functional.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/_functional.pyi @@ -8,7 +8,7 @@ if sys.version_info >= (3, 13): from importlib.resources._common import Anchor from io import TextIOWrapper from pathlib import Path - from typing import BinaryIO, overload + from typing import BinaryIO, Literal, overload from typing_extensions import Unpack def open_binary(anchor: Anchor, *path_names: StrPath) -> BinaryIO: ... @@ -25,6 +25,6 @@ if sys.version_info >= (3, 13): ) -> str: ... @overload def read_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> str: ... - def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path]: ... + def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path, Literal[False]]: ... def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: ... def contents(anchor: Anchor, *path_names: StrPath) -> Iterator[str]: ... diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 229eb2135690..5bebe9bf4482 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -345,12 +345,12 @@ class Signature: if sys.version_info >= (3, 10): def get_annotations( - obj: Callable[..., object] | type[Any] | ModuleType, + obj: Callable[..., object] | type[object] | ModuleType, # any callable, class, or module *, - globals: Mapping[str, Any] | None = None, - locals: Mapping[str, Any] | None = None, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key eval_str: bool = False, - ) -> dict[str, Any]: ... + ) -> dict[str, Any]: ... # values are type expressions # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index 5c444e66c4c7..000ba1ebb06e 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -4,7 +4,7 @@ from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence from configparser import RawConfigParser from re import Pattern from threading import Thread -from typing import IO, Any, Final, Literal, SupportsIndex, TypedDict, overload +from typing import IO, Any, Final, Literal, SupportsIndex, TypedDict, overload, type_check_only from typing_extensions import Required, TypeAlias from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level @@ -14,17 +14,20 @@ RESET_ERROR: Final[int] # undocumented IDENTIFIER: Final[Pattern[str]] # undocumented if sys.version_info >= (3, 11): + @type_check_only class _RootLoggerConfiguration(TypedDict, total=False): level: _Level filters: Sequence[str | _FilterType] handlers: Sequence[str] else: + @type_check_only class _RootLoggerConfiguration(TypedDict, total=False): level: _Level filters: Sequence[str] handlers: Sequence[str] +@type_check_only class _LoggerConfiguration(_RootLoggerConfiguration, TypedDict, total=False): propagate: bool @@ -32,6 +35,7 @@ _FormatterConfigurationTypedDict = TypedDict( "_FormatterConfigurationTypedDict", {"class": str, "format": str, "datefmt": str, "style": _FormatStyle}, total=False ) +@type_check_only class _FilterConfigurationTypedDict(TypedDict): name: str @@ -43,6 +47,7 @@ _FilterConfiguration: TypeAlias = _FilterConfigurationTypedDict | dict[str, Any] # Handler config can have additional keys even when not providing a custom factory so we just use `dict`. _HandlerConfiguration: TypeAlias = dict[str, Any] +@type_check_only class _DictConfigArgs(TypedDict, total=False): version: Required[Literal[1]] formatters: dict[str, _FormatterConfiguration] diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 7e7fa4fda9a1..59d70779c72f 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import SupportsRead +from _typeshed import StrOrBytesPath, SupportsRead from _typeshed.importlib import LoaderProtocol, MetaPathFinderProtocol, PathEntryFinderProtocol from collections.abc import Callable, Iterable, Iterator from typing import IO, Any, NamedTuple, TypeVar @@ -31,21 +31,21 @@ def extend_path(path: _PathT, name: str) -> _PathT: ... if sys.version_info < (3, 12): class ImpImporter: - def __init__(self, path: str | None = None) -> None: ... + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... class ImpLoader: - def __init__(self, fullname: str, file: IO[str], filename: str, etc: tuple[str, str, int]) -> None: ... + def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ... @deprecated("Use importlib.util.find_spec() instead. Will be removed in Python 3.14.") def find_loader(fullname: str) -> LoaderProtocol | None: ... -def get_importer(path_item: str) -> PathEntryFinderProtocol | None: ... +def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: ... @deprecated("Use importlib.util.find_spec() instead. Will be removed in Python 3.14.") def get_loader(module_or_name: str) -> LoaderProtocol | None: ... def iter_importers(fullname: str = "") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: ... -def iter_modules(path: Iterable[str] | None = None, prefix: str = "") -> Iterator[ModuleInfo]: ... +def iter_modules(path: Iterable[StrOrBytesPath] | None = None, prefix: str = "") -> Iterator[ModuleInfo]: ... def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented def walk_packages( - path: Iterable[str] | None = None, prefix: str = "", onerror: Callable[[str], object] | None = None + path: Iterable[StrOrBytesPath] | None = None, prefix: str = "", onerror: Callable[[str], object] | None = None ) -> Iterator[ModuleInfo]: ... def get_data(package: str, resource: str) -> bytes | None: ... diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index c8ecbbceab1a..9418bdea9d6d 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -3,7 +3,7 @@ from _typeshed import SupportsRichComparisonT from collections.abc import Callable, Hashable, Iterable, Sequence from decimal import Decimal from fractions import Fraction -from typing import Any, Literal, NamedTuple, SupportsFloat, TypeVar +from typing import Literal, NamedTuple, SupportsFloat, SupportsIndex, TypeVar from typing_extensions import Self, TypeAlias __all__ = [ @@ -38,6 +38,9 @@ _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) # Used in mode, multimode _HashableT = TypeVar("_HashableT", bound=Hashable) +# Used in NormalDist.samples and kde_random +_Seed: TypeAlias = int | float | str | bytes | bytearray # noqa: Y041 + class StatisticsError(ValueError): ... if sys.version_info >= (3, 11): @@ -89,7 +92,7 @@ class NormalDist: def variance(self) -> float: ... @classmethod def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: ... - def samples(self, n: int, *, seed: Any | None = None) -> list[float]: ... + def samples(self, n: SupportsIndex, *, seed: _Seed | None = None) -> list[float]: ... def pdf(self, x: float) -> float: ... def cdf(self, x: float) -> float: ... def inv_cdf(self, p: float) -> float: ... @@ -98,15 +101,15 @@ class NormalDist: if sys.version_info >= (3, 9): def zscore(self, x: float) -> float: ... - def __eq__(self, x2: object) -> bool: ... - def __add__(self, x2: float | NormalDist) -> NormalDist: ... - def __sub__(self, x2: float | NormalDist) -> NormalDist: ... - def __mul__(self, x2: float) -> NormalDist: ... - def __truediv__(self, x2: float) -> NormalDist: ... - def __pos__(self) -> NormalDist: ... - def __neg__(self) -> NormalDist: ... + def __eq__(x1, x2: object) -> bool: ... + def __add__(x1, x2: float | NormalDist) -> NormalDist: ... + def __sub__(x1, x2: float | NormalDist) -> NormalDist: ... + def __mul__(x1, x2: float) -> NormalDist: ... + def __truediv__(x1, x2: float) -> NormalDist: ... + def __pos__(x1) -> NormalDist: ... + def __neg__(x1) -> NormalDist: ... __radd__ = __add__ - def __rsub__(self, x2: float | NormalDist) -> NormalDist: ... + def __rsub__(x1, x2: float | NormalDist) -> NormalDist: ... __rmul__ = __mul__ def __hash__(self) -> int: ... @@ -153,9 +156,5 @@ if sys.version_info >= (3, 13): data: Sequence[float], h: float, kernel: _Kernel = "normal", *, cumulative: bool = False ) -> Callable[[float], float]: ... def kde_random( - data: Sequence[float], - h: float, - kernel: _Kernel = "normal", - *, - seed: int | float | str | bytes | bytearray | None = None, # noqa: Y041 + data: Sequence[float], h: float, kernel: _Kernel = "normal", *, seed: _Seed | None = None ) -> Callable[[], float]: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 751de523bf7a..73c1e0400fe8 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -265,7 +265,7 @@ else: GraphicsExpose = "13" Gravity = "24" KeyPress = "2" - Key = "2" + Key = KeyPress KeyRelease = "3" Keymap = "11" Leave = "8" diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 849db3ece938..542979d4afc5 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -687,6 +687,8 @@ if sys.version_info >= (3, 10): class UnionType: @property def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... def __or__(self, value: Any, /) -> UnionType: ... def __ror__(self, value: Any, /) -> UnionType: ... def __eq__(self, value: object, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 5875b6915762..bc8f342ef46b 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -130,8 +130,7 @@ if sys.version_info >= (3, 12): if sys.version_info >= (3, 13): __all__ += ["get_protocol_members", "is_protocol", "NoDefault", "TypeIs", "ReadOnly"] -Any = object() - +class Any: ... class _Final: ... def final(f: _T) -> _T: ... @@ -950,6 +949,9 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): # so we only add it to the stub on 3.12+ if sys.version_info >= (3, 12): __orig_bases__: ClassVar[tuple[Any, ...]] + if sys.version_info >= (3, 13): + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] def copy(self) -> typing_extensions.Self: ... # Using Never so that only calls using mypy plugin hook that specialize the signature @@ -957,7 +959,7 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def setdefault(self, k: _Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: _Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] - def update(self: _T, m: _T, /) -> None: ... + def update(self, m: typing_extensions.Self, /) -> None: ... def __delitem__(self, k: _Never) -> None: ... def items(self) -> dict_items[str, object]: ... def keys(self) -> dict_keys[str, object]: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index fd98722b10a8..f3b7b8ddf5b1 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,9 +1,11 @@ import abc +import enum import sys import typing from _collections_abc import dict_items, dict_keys, dict_values -from _typeshed import IdentityFunction +from _typeshed import IdentityFunction, Incomplete, Unused from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager +from types import ModuleType from typing import ( # noqa: Y022,Y037,Y038,Y039 IO as IO, TYPE_CHECKING as TYPE_CHECKING, @@ -68,9 +70,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 9): from types import GenericAlias +# Please keep order the same as at runtime. __all__ = [ + # Super-special typing primitives. "Any", - "Buffer", "ClassVar", "Concatenate", "Final", @@ -83,14 +86,16 @@ __all__ = [ "TypeVar", "TypeVarTuple", "Unpack", + # ABCs (from collections.abc). "Awaitable", "AsyncIterator", "AsyncIterable", "Coroutine", "AsyncGenerator", "AsyncContextManager", - "CapsuleType", + "Buffer", "ChainMap", + # Concrete collection types. "ContextManager", "Counter", "Deque", @@ -98,20 +103,34 @@ __all__ = [ "NamedTuple", "OrderedDict", "TypedDict", - "SupportsIndex", + # Structural checks, a.k.a. protocols. "SupportsAbs", - "SupportsRound", "SupportsBytes", "SupportsComplex", "SupportsFloat", + "SupportsIndex", "SupportsInt", + "SupportsRound", + # One-off things. "Annotated", "assert_never", "assert_type", + "clear_overloads", "dataclass_transform", "deprecated", + "Doc", + "evaluate_forward_ref", + "get_overloads", "final", + "Format", + "get_annotations", + "get_args", + "get_origin", + "get_original_bases", + "get_protocol_members", + "get_type_hints", "IntVar", + "is_protocol", "is_typeddict", "Literal", "NewType", @@ -124,18 +143,18 @@ __all__ = [ "Text", "TypeAlias", "TypeAliasType", + "TypeForm", "TypeGuard", + "TypeIs", "TYPE_CHECKING", "Never", "NoReturn", + "ReadOnly", "Required", "NotRequired", - "clear_overloads", - "get_args", - "get_origin", - "get_original_bases", - "get_overloads", - "get_type_hints", + "NoDefault", + "NoExtraItems", + # Pure aliases, have always been in typing "AbstractSet", "AnyStr", "BinaryIO", @@ -143,7 +162,6 @@ __all__ = [ "Collection", "Container", "Dict", - "Doc", "ForwardRef", "FrozenSet", "Generator", @@ -161,7 +179,6 @@ __all__ = [ "MutableMapping", "MutableSequence", "MutableSet", - "NoDefault", "Optional", "Pattern", "Reversible", @@ -173,12 +190,10 @@ __all__ = [ "Union", "ValuesView", "cast", - "get_protocol_members", - "is_protocol", "no_type_check", "no_type_check_decorator", - "ReadOnly", - "TypeIs", + # Added dynamically + "CapsuleType", ] _T = typing.TypeVar("_T") @@ -234,7 +249,7 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def setdefault(self, k: Never, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] - def update(self: _T, m: _T, /) -> None: ... + def update(self, m: Self, /) -> None: ... def items(self) -> dict_items[str, object]: ... def keys(self) -> dict_keys[str, object]: ... def values(self) -> dict_values[str, object]: ... @@ -382,33 +397,11 @@ if sys.version_info >= (3, 12): SupportsIndex as SupportsIndex, SupportsInt as SupportsInt, SupportsRound as SupportsRound, - TypeAliasType as TypeAliasType, override as override, ) else: def override(arg: _F, /) -> _F: ... def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... - @final - class TypeAliasType: - def __init__( - self, name: str, value: Any, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = () - ) -> None: ... - @property - def __value__(self) -> Any: ... - @property - def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ... - @property - def __parameters__(self) -> tuple[Any, ...]: ... - @property - def __name__(self) -> str: ... - # It's writable on types, but not on instances of TypeAliasType. - @property - def __module__(self) -> str | None: ... # type: ignore[override] - # Returns typing._GenericAlias, which isn't stubbed. - def __getitem__(self, parameters: Any) -> Any: ... - if sys.version_info >= (3, 10): - def __or__(self, right: Any) -> _SpecialForm: ... - def __ror__(self, left: Any) -> _SpecialForm: ... # mypy and pyright object to this being both ABC and Protocol. # At runtime it inherits from ABC and is not a Protocol, but it is on the @@ -569,8 +562,71 @@ else: ReadOnly: _SpecialForm TypeIs: _SpecialForm +# TypeAliasType was added in Python 3.12, but had significant changes in 3.14. +if sys.version_info >= (3, 14): + from typing import TypeAliasType as TypeAliasType +else: + @final + class TypeAliasType: + def __init__( + self, name: str, value: Any, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = () + ) -> None: ... # value is a type expression + @property + def __value__(self) -> Any: ... # a type expression + @property + def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ... + @property + # `__parameters__` can include special forms if a `TypeVarTuple` was + # passed as a `type_params` element to the constructor method. + def __parameters__(self) -> tuple[TypeVar | ParamSpec | Any, ...]: ... + @property + def __name__(self) -> str: ... + # It's writable on types, but not on instances of TypeAliasType. + @property + def __module__(self) -> str | None: ... # type: ignore[override] + # Returns typing._GenericAlias, which isn't stubbed. + def __getitem__(self, parameters: Incomplete | tuple[Incomplete, ...]) -> Any: ... + def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> NoReturn: ... + if sys.version_info >= (3, 10): + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... + +# PEP 727 class Doc: documentation: str def __init__(self, documentation: str, /) -> None: ... def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... + +# PEP 728 +class _NoExtraItemsType: ... + +NoExtraItems: _NoExtraItemsType + +# PEP 747 +TypeForm: _SpecialForm + +class Format(enum.IntEnum): + VALUE = 1 + FORWARDREF = 2 + STRING = 3 + +# PEP 649/749 +def get_annotations( + obj: Callable[..., object] | type[object] | ModuleType, # any callable, class, or module + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Format = Format.VALUE, # noqa: Y011 +) -> dict[str, Any]: ... # values are type expressions +def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Format = Format.VALUE, # noqa: Y011 + _recursive_guard: Container[str] = ..., +) -> Any: ... # str if format is Format.STRING, otherwise a type expression diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index 533a36817506..49c98cb07540 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -3,8 +3,8 @@ import sys from _warnings import warn as warn, warn_explicit as warn_explicit from collections.abc import Sequence from types import ModuleType, TracebackType -from typing import Any, Generic, Literal, TextIO, TypeVar, overload -from typing_extensions import LiteralString, TypeAlias +from typing import Any, Generic, Literal, TextIO, overload +from typing_extensions import LiteralString, TypeAlias, TypeVar __all__ = [ "warn", @@ -21,7 +21,8 @@ if sys.version_info >= (3, 13): __all__ += ["deprecated"] _T = TypeVar("_T") -_W = TypeVar("_W", bound=list[WarningMessage] | None) +_W_co = TypeVar("_W_co", bound=list[WarningMessage] | None, default=list[WarningMessage] | None, covariant=True) + if sys.version_info >= (3, 14): _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] else: @@ -66,7 +67,7 @@ class WarningMessage: source: Any | None = None, ) -> None: ... -class catch_warnings(Generic[_W]): +class catch_warnings(Generic[_W_co]): if sys.version_info >= (3, 11): @overload def __init__( @@ -92,7 +93,7 @@ class catch_warnings(Generic[_W]): ) -> None: ... @overload def __init__( - self: catch_warnings[list[WarningMessage] | None], + self, *, record: bool, module: ModuleType | None = None, @@ -109,11 +110,9 @@ class catch_warnings(Generic[_W]): self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None ) -> None: ... @overload - def __init__( - self: catch_warnings[list[WarningMessage] | None], *, record: bool, module: ModuleType | None = None - ) -> None: ... + def __init__(self, *, record: bool, module: ModuleType | None = None) -> None: ... - def __enter__(self) -> _W: ... + def __enter__(self) -> _W_co: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ...