From b1d9e5227e9f6a3512a36ff0095fc8cc7d79663b Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Tue, 10 May 2022 21:50:54 -0700 Subject: [PATCH 1/3] Sync typeshed Source commit: https://github.com/python/typeshed/commit/b00b4f34473111c08b44ea00a7094dda51214891 --- mypy/typeshed/stdlib/_ast.pyi | 2 +- mypy/typeshed/stdlib/_csv.pyi | 62 +- mypy/typeshed/stdlib/_decimal.pyi | 18 +- mypy/typeshed/stdlib/_socket.pyi | 4 + mypy/typeshed/stdlib/_typeshed/__init__.pyi | 25 +- mypy/typeshed/stdlib/asyncio/transports.pyi | 6 +- mypy/typeshed/stdlib/builtins.pyi | 70 ++- mypy/typeshed/stdlib/contextlib.pyi | 4 +- mypy/typeshed/stdlib/csv.pyi | 49 +- mypy/typeshed/stdlib/dataclasses.pyi | 22 +- mypy/typeshed/stdlib/datetime.pyi | 7 +- mypy/typeshed/stdlib/enum.pyi | 20 +- mypy/typeshed/stdlib/http/__init__.pyi | 22 +- mypy/typeshed/stdlib/inspect.pyi | 73 ++- mypy/typeshed/stdlib/logging/__init__.pyi | 2 +- .../stdlib/multiprocessing/managers.pyi | 18 +- mypy/typeshed/stdlib/os/__init__.pyi | 4 + mypy/typeshed/stdlib/posix.pyi | 3 + mypy/typeshed/stdlib/re.pyi | 70 ++- mypy/typeshed/stdlib/socket.pyi | 23 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 2 + mypy/typeshed/stdlib/subprocess.pyi | 559 +++++++++++++++++- mypy/typeshed/stdlib/sys.pyi | 8 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 178 +++++- mypy/typeshed/stdlib/types.pyi | 4 + mypy/typeshed/stdlib/typing.pyi | 65 +- mypy/typeshed/stdlib/typing_extensions.pyi | 20 +- mypy/typeshed/stdlib/urllib/error.pyi | 2 + mypy/typeshed/stdlib/warnings.pyi | 49 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 2 +- mypy/typeshed/stdlib/zipfile.pyi | 2 + .../stubs/mypy-extensions/METADATA.toml | 1 - .../stubs/mypy-extensions/mypy_extensions.pyi | 17 +- 33 files changed, 1241 insertions(+), 172 deletions(-) diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index cb13c7452081..1305b0c94d9b 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -319,7 +319,7 @@ class FormattedValue(expr): if sys.version_info >= (3, 10): __match_args__ = ("value", "conversion", "format_spec") value: expr - conversion: int | None + conversion: int format_spec: expr | None class JoinedStr(expr): diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index ae9031df6e81..7d15365d3b02 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -1,5 +1,6 @@ +from _typeshed import SupportsWrite from collections.abc import Iterable, Iterator -from typing import Any, Protocol, Union +from typing import Any, Union from typing_extensions import Literal, TypeAlias __version__: str @@ -9,6 +10,10 @@ QUOTE_MINIMAL: Literal[0] QUOTE_NONE: Literal[3] QUOTE_NONNUMERIC: Literal[2] +# Ideally this would be `QUOTE_ALL | QUOTE_MINIMAL | QUOTE_NONE | QUOTE_NONNUMERIC` +# However, using literals in situations like these can cause false-positives (see #7258) +_QuotingType: TypeAlias = int + class Error(Exception): ... class Dialect: @@ -18,28 +23,63 @@ class Dialect: doublequote: bool skipinitialspace: bool lineterminator: str - quoting: int - strict: int + quoting: _QuotingType + strict: bool def __init__(self) -> None: ... _DialectLike: TypeAlias = Union[str, Dialect, type[Dialect]] class _reader(Iterator[list[str]]): - dialect: Dialect + @property + def dialect(self) -> Dialect: ... line_num: int def __next__(self) -> list[str]: ... class _writer: - dialect: Dialect + @property + def dialect(self) -> Dialect: ... def writerow(self, row: Iterable[Any]) -> Any: ... def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... -class _Writer(Protocol): - def write(self, __s: str) -> object: ... - -def writer(csvfile: _Writer, dialect: _DialectLike = ..., **fmtparams: Any) -> _writer: ... -def reader(csvfile: Iterable[str], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... -def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... +def writer( + csvfile: SupportsWrite[str], + dialect: _DialectLike = ..., + *, + delimiter: str = ..., + quotechar: str | None = ..., + escapechar: str | None = ..., + doublequote: bool = ..., + skipinitialspace: bool = ..., + lineterminator: str = ..., + quoting: _QuotingType = ..., + strict: bool = ..., +) -> _writer: ... +def reader( + csvfile: Iterable[str], + dialect: _DialectLike = ..., + *, + delimiter: str = ..., + quotechar: str | None = ..., + escapechar: str | None = ..., + doublequote: bool = ..., + skipinitialspace: bool = ..., + lineterminator: str = ..., + quoting: _QuotingType = ..., + strict: bool = ..., +) -> _reader: ... +def register_dialect( + name: str, + dialect: Any = ..., + *, + delimiter: str = ..., + quotechar: str | None = ..., + escapechar: str | None = ..., + doublequote: bool = ..., + skipinitialspace: bool = ..., + lineterminator: str = ..., + quoting: _QuotingType = ..., + strict: bool = ..., +) -> None: ... def unregister_dialect(name: str) -> None: ... def get_dialect(name: str) -> Dialect: ... def list_dialects() -> list[str]: ... diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index fdeca8f7c42f..a259058ee163 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -52,7 +52,23 @@ class FloatOperation(DecimalException, TypeError): ... def setcontext(__context: Context) -> None: ... def getcontext() -> Context: ... -def localcontext(ctx: Context | None = ...) -> _ContextManager: ... + +if sys.version_info >= (3, 11): + def localcontext( + ctx: Context | None = ..., + *, + prec: int | None = ..., + rounding: str | None = ..., + Emin: int | None = ..., + Emax: int | None = ..., + capitals: int | None = ..., + clamp: int | None = ..., + traps: dict[_TrapType, bool] | None = ..., + flags: dict[_TrapType, bool] | None = ..., + ) -> _ContextManager: ... + +else: + def localcontext(ctx: Context | None = ...) -> _ContextManager: ... class Decimal: def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 2366412050cd..e49cdfbb983a 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -256,6 +256,8 @@ SO_SNDLOWAT: int SO_SNDTIMEO: int SO_TYPE: int SO_USELOOPBACK: int +if sys.platform == "linux" and sys.version_info >= (3, 11): + SO_INCOMING_CPU: int TCP_CORK: int TCP_DEFER_ACCEPT: int TCP_FASTOPEN: int @@ -271,6 +273,8 @@ TCP_SYNCNT: int TCP_WINDOW_CLAMP: int if sys.version_info >= (3, 7): TCP_NOTSENT_LOWAT: int +if sys.version_info >= (3, 11) and sys.platform == "darwin": + TCP_CONNECTION_INFO: int # Specifically-documented constants diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index a80ea0702f77..d5e0c691e8c0 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -5,6 +5,7 @@ import array import ctypes import mmap +import pickle import sys from collections.abc import Awaitable, Container, Iterable, Set as AbstractSet from os import PathLike @@ -63,12 +64,27 @@ class SupportsAllComparisons(SupportsDunderLT, SupportsDunderGT, SupportsDunderL SupportsRichComparison: TypeAlias = SupportsDunderLT | SupportsDunderGT SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichComparison) # noqa: Y001 +# Dunder protocols + +class SupportsAdd(Protocol): + def __add__(self, __x: Any) -> Any: ... + class SupportsDivMod(Protocol[_T_contra, _T_co]): def __divmod__(self, __other: _T_contra) -> _T_co: ... class SupportsRDivMod(Protocol[_T_contra, _T_co]): def __rdivmod__(self, __other: _T_contra) -> _T_co: ... +# This protocol is generic over the iterator type, while Iterable is +# generic over the type that is iterated over. +class SupportsIter(Protocol[_T_co]): + def __iter__(self) -> _T_co: ... + +# This protocol is generic over the iterator type, while AsyncIterable is +# generic over the type that is iterated over. +class SupportsAiter(Protocol[_T_co]): + def __aiter__(self) -> _T_co: ... + class SupportsLenAndGetItem(Protocol[_T_co]): def __len__(self) -> int: ... def __getitem__(self, __k: int) -> _T_co: ... @@ -194,8 +210,13 @@ class SupportsWrite(Protocol[_T_contra]): ReadOnlyBuffer: TypeAlias = bytes # stable # Anything that implements the read-write buffer interface. # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol -# for it. Instead we have to list the most common stdlib buffer classes in a Union. -WriteableBuffer: TypeAlias = bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData # stable +# for it (until PEP 688 is implemented). Instead we have to list the most common stdlib buffer classes in a Union. +if sys.version_info >= (3, 8): + WriteableBuffer: TypeAlias = ( + bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData | pickle.PickleBuffer + ) # stable +else: + WriteableBuffer: TypeAlias = bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData # stable # Same as _WriteableBuffer, but also includes read-only buffer types (like bytes). ReadableBuffer: TypeAlias = ReadOnlyBuffer | WriteableBuffer # stable diff --git a/mypy/typeshed/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi index a8cd753c2af8..7e17beb9f630 100644 --- a/mypy/typeshed/stdlib/asyncio/transports.pyi +++ b/mypy/typeshed/stdlib/asyncio/transports.pyi @@ -28,9 +28,7 @@ class ReadTransport(BaseTransport): class WriteTransport(BaseTransport): def set_write_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... def get_write_buffer_size(self) -> int: ... - if sys.version_info >= (3, 9): - def get_write_buffer_limits(self) -> tuple[int, int]: ... - + def get_write_buffer_limits(self) -> tuple[int, int]: ... def write(self, data: Any) -> None: ... def writelines(self, list_of_data: list[Any]) -> None: ... def write_eof(self) -> None: ... @@ -53,4 +51,6 @@ class SubprocessTransport(BaseTransport): class _FlowControlMixin(Transport): def __init__(self, extra: Mapping[Any, Any] | None = ..., loop: AbstractEventLoop | None = ...) -> None: ... + def set_write_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... + def get_write_buffer_size(self) -> int: ... def get_write_buffer_limits(self) -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index bf1e6cde2c08..9e04ac4e50a3 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -11,8 +11,11 @@ from _typeshed import ( ReadableBuffer, Self, StrOrBytesPath, + SupportsAdd, + SupportsAiter, SupportsAnext, SupportsDivMod, + SupportsIter, SupportsKeysAndGetItem, SupportsLenAndGetItem, SupportsNext, @@ -71,12 +74,6 @@ _SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant _AwaitableT = TypeVar("_AwaitableT", bound=Awaitable[Any]) _AwaitableT_co = TypeVar("_AwaitableT_co", bound=Awaitable[Any], covariant=True) -class _SupportsIter(Protocol[_T_co]): - def __iter__(self) -> _T_co: ... - -class _SupportsAiter(Protocol[_T_co]): - def __aiter__(self) -> _T_co: ... - class object: __doc__: str | None __dict__: dict[str, Any] @@ -122,7 +119,8 @@ class staticmethod(Generic[_R_co]): if sys.version_info >= (3, 10): __name__: str __qualname__: str - __wrapped__: Callable[..., _R_co] + @property + def __wrapped__(self) -> Callable[..., _R_co]: ... def __call__(self, *args: Any, **kwargs: Any) -> _R_co: ... class classmethod(Generic[_R_co]): @@ -135,7 +133,8 @@ class classmethod(Generic[_R_co]): if sys.version_info >= (3, 10): __name__: str __qualname__: str - __wrapped__: Callable[..., _R_co] + @property + def __wrapped__(self) -> Callable[..., _R_co]: ... class type: @property @@ -255,7 +254,9 @@ class int: @overload def __pow__(self, __x: int, __modulo: int) -> int: ... @overload - def __pow__(self, __x: Literal[0], __modulo: None = ...) -> Literal[1]: ... + def __pow__(self, __x: Literal[0]) -> Literal[1]: ... + @overload + def __pow__(self, __x: Literal[0], __modulo: None) -> Literal[1]: ... @overload def __pow__(self, __x: _PositiveInteger, __modulo: None = ...) -> int: ... @overload @@ -328,7 +329,12 @@ class float: def __rtruediv__(self, __x: float) -> float: ... def __rmod__(self, __x: float) -> float: ... def __rdivmod__(self, __x: float) -> tuple[float, float]: ... - # Returns complex if the argument is negative. + @overload + def __rpow__(self, __x: _PositiveInteger, __modulo: None = ...) -> float: ... + @overload + def __rpow__(self, __x: _NegativeInteger, __mod: None = ...) -> complex: ... + # Returning `complex` for the general case gives too many false-positive errors. + @overload def __rpow__(self, __x: float, __mod: None = ...) -> Any: ... def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... @@ -1092,7 +1098,7 @@ class _PathLike(Protocol[_AnyStr_co]): def __fspath__(self) -> _AnyStr_co: ... if sys.version_info >= (3, 10): - def aiter(__async_iterable: _SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... + def aiter(__async_iterable: SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): def __anext__(self) -> _AwaitableT_co: ... @@ -1144,9 +1150,22 @@ def eval( ) -> Any: ... # Comment above regarding `eval` applies to `exec` as well -def exec( - __source: str | ReadableBuffer | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... -) -> None: ... +if sys.version_info >= (3, 11): + def exec( + __source: str | ReadableBuffer | CodeType, + __globals: dict[str, Any] | None = ..., + __locals: Mapping[str, object] | None = ..., + *, + closure: tuple[_Cell, ...] | None = ..., + ) -> None: ... + +else: + def exec( + __source: str | ReadableBuffer | CodeType, + __globals: dict[str, Any] | None = ..., + __locals: Mapping[str, object] | None = ..., + ) -> None: ... + def exit(code: object = ...) -> NoReturn: ... class filter(Iterator[_T], Generic[_T]): @@ -1183,8 +1202,14 @@ def help(request: object = ...) -> None: ... def hex(__number: int | SupportsIndex) -> str: ... def id(__obj: object) -> int: ... def input(__prompt: object = ...) -> str: ... + +class _GetItemIterable(Protocol[_T_co]): + def __getitem__(self, __i: int) -> _T_co: ... + @overload -def iter(__iterable: _SupportsIter[_SupportsNextT]) -> _SupportsNextT: ... +def iter(__iterable: SupportsIter[_SupportsNextT]) -> _SupportsNextT: ... +@overload +def iter(__iterable: _GetItemIterable[_T]) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload @@ -1423,6 +1448,10 @@ if sys.version_info >= (3, 8): @overload def pow(base: int, exp: int, mod: None = ...) -> Any: ... @overload + def pow(base: _PositiveInteger, exp: float, mod: None = ...) -> float: ... + @overload + def pow(base: _NegativeInteger, exp: float, mod: None = ...) -> complex: ... + @overload def pow(base: float, exp: int, mod: None = ...) -> float: ... # float base & float exp could return float or complex # return type must be Any (same as complex base, complex exp), @@ -1456,6 +1485,10 @@ else: @overload def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... @overload + def pow(__base: _PositiveInteger, __exp: float, __mod: None = ...) -> float: ... + @overload + def pow(__base: _NegativeInteger, __exp: float, __mod: None = ...) -> complex: ... + @overload def pow(__base: float, __exp: int, __mod: None = ...) -> float: ... @overload def pow(__base: float, __exp: complex | _SupportsSomeKindOfPow, __mod: None = ...) -> Any: ... @@ -1501,11 +1534,8 @@ def sorted( @overload def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ... -class _SupportsSum(Protocol): - def __add__(self, __x: Any) -> Any: ... - -_SumT = TypeVar("_SumT", bound=_SupportsSum) -_SumS = TypeVar("_SumS", bound=_SupportsSum) +_SumT = TypeVar("_SumT", bound=SupportsAdd) +_SumS = TypeVar("_SumS", bound=SupportsAdd) @overload def sum(__iterable: Iterable[_SumT]) -> _SumT | Literal[0]: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index c93eeac3b44f..1b6ee4298174 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -78,7 +78,7 @@ _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", AbstractContextManager[Any], _ExitFunc) +_CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any] | _ExitFunc) class ContextDecorator: def __call__(self, func: _F) -> _F: ... @@ -177,7 +177,7 @@ class ExitStack(AbstractContextManager[ExitStack]): if sys.version_info >= (3, 7): _ExitCoroFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] - _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) + _ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any] | _ExitCoroFunc) class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index dcb3f19bebe1..de69c71ad941 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -1,4 +1,6 @@ import sys + +# actually csv.Dialect is a different class to _csv.Dialect at runtime, but for typing purposes, they're identical from _csv import ( QUOTE_ALL as QUOTE_ALL, QUOTE_MINIMAL as QUOTE_MINIMAL, @@ -8,6 +10,7 @@ from _csv import ( Error as Error, __version__ as __version__, _DialectLike, + _QuotingType, _reader, _writer, field_size_limit as field_size_limit, @@ -18,9 +21,10 @@ from _csv import ( unregister_dialect as unregister_dialect, writer as writer, ) -from _typeshed import Self +from _typeshed import Self, SupportsWrite from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence from typing import Any, Generic, TypeVar, overload +from typing_extensions import Literal if sys.version_info >= (3, 8): from builtins import dict as _DictReadMapping @@ -59,7 +63,7 @@ class excel(Dialect): doublequote: bool skipinitialspace: bool lineterminator: str - quoting: int + quoting: _QuotingType class excel_tab(excel): delimiter: str @@ -70,7 +74,7 @@ class unix_dialect(Dialect): doublequote: bool skipinitialspace: bool lineterminator: str - quoting: int + quoting: _QuotingType class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): fieldnames: Sequence[_T] | None @@ -87,8 +91,15 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): restkey: str | None = ..., restval: str | None = ..., dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, + *, + delimiter: str = ..., + quotechar: str | None = ..., + escapechar: str | None = ..., + doublequote: bool = ..., + skipinitialspace: bool = ..., + lineterminator: str = ..., + quoting: _QuotingType = ..., + strict: bool = ..., ) -> None: ... @overload def __init__( @@ -98,8 +109,15 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): restkey: str | None = ..., restval: str | None = ..., dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, + *, + delimiter: str = ..., + quotechar: str | None = ..., + escapechar: str | None = ..., + doublequote: bool = ..., + skipinitialspace: bool = ..., + lineterminator: str = ..., + quoting: _QuotingType = ..., + strict: bool = ..., ) -> None: ... def __iter__(self: Self) -> Self: ... def __next__(self) -> _DictReadMapping[_T, str]: ... @@ -107,17 +125,24 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): class DictWriter(Generic[_T]): fieldnames: Collection[_T] restval: Any | None - extrasaction: str + extrasaction: Literal["raise", "ignore"] writer: _writer def __init__( self, - f: Any, + f: SupportsWrite[str], fieldnames: Collection[_T], restval: Any | None = ..., - extrasaction: str = ..., + extrasaction: Literal["raise", "ignore"] = ..., dialect: _DialectLike = ..., - *args: Any, - **kwds: Any, + *, + delimiter: str = ..., + quotechar: str | None = ..., + escapechar: str | None = ..., + doublequote: bool = ..., + skipinitialspace: bool = ..., + lineterminator: str = ..., + quoting: _QuotingType = ..., + strict: bool = ..., ) -> None: ... if sys.version_info >= (3, 8): def writeheader(self) -> Any: ... diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index f58c6f9f1460..1cbf998dd303 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -79,7 +79,23 @@ else: @overload def dataclass(_cls: None) -> Callable[[type[_T]], type[_T]]: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 11): + @overload + def dataclass( + *, + init: bool = ..., + repr: bool = ..., + eq: bool = ..., + order: bool = ..., + unsafe_hash: bool = ..., + frozen: bool = ..., + match_args: bool = ..., + kw_only: bool = ..., + slots: bool = ..., + weakref_slot: bool = ..., + ) -> Callable[[type[_T]], type[_T]]: ... + +elif sys.version_info >= (3, 10): @overload def dataclass( *, @@ -227,7 +243,7 @@ class InitVar(Generic[_T]): if sys.version_info >= (3, 10): def make_dataclass( cls_name: str, - fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], + fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]], *, bases: tuple[type, ...] = ..., namespace: dict[str, Any] | None = ..., @@ -245,7 +261,7 @@ if sys.version_info >= (3, 10): else: def make_dataclass( cls_name: str, - fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], + fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]], *, bases: tuple[type, ...] = ..., namespace: dict[str, Any] | None = ..., diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 113c679743fd..e2a359d0a536 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -4,7 +4,9 @@ from time import struct_time from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, TypeVar, overload from typing_extensions import Literal, TypeAlias, final -if sys.version_info >= (3, 9): +if sys.version_info >= (3, 11): + __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") +elif sys.version_info >= (3, 9): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") _D = TypeVar("_D", bound=date) @@ -29,6 +31,9 @@ class timezone(tzinfo): def __init__(self, offset: timedelta, name: str = ...) -> None: ... def __hash__(self) -> int: ... +if sys.version_info >= (3, 11): + UTC: timezone + if sys.version_info >= (3, 9): class _IsoCalendarDate(NamedTuple): year: int diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index a7c84c5b1c0d..9ebeba37ab71 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -4,7 +4,7 @@ from _typeshed import Self from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping -from typing import Any, TypeVar, overload +from typing import Any, Generic, TypeVar, overload from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 11): @@ -21,6 +21,8 @@ if sys.version_info >= (3, 11): "unique", "property", "verify", + "member", + "nonmember", "FlagBoundary", "STRICT", "CONFORM", @@ -54,6 +56,15 @@ _EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) # _EnumNames: TypeAlias = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] +if sys.version_info >= (3, 11): + class nonmember(Generic[_EnumMemberT]): + value: _EnumMemberT + def __init__(self, value: _EnumMemberT) -> None: ... + + class member(Generic[_EnumMemberT]): + value: _EnumMemberT + def __init__(self, value: _EnumMemberT) -> None: ... + class _EnumDict(dict[str, Any]): def __init__(self) -> None: ... def __setitem__(self, key: str, value: Any) -> None: ... @@ -155,7 +166,12 @@ class Enum(metaclass=EnumMeta): def _missing_(cls, value: object) -> Any: ... @staticmethod def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: ... - def __new__(cls: type[Self], value: Any) -> Self: ... + # It's not true that `__new__` will accept any argument type, + # so ideally we'd use `Any` to indicate that the argument type is inexpressible. + # However, using `Any` causes too many false-positives for those using mypy's `--disallow-any-expr` + # (see #7752, #2539, mypy/#5788), + # and in practice using `object` here has the same effect as using `Any`. + def __new__(cls: type[Self], value: object) -> Self: ... def __dir__(self) -> list[str]: ... def __format__(self, format_spec: str) -> str: ... def __hash__(self) -> Any: ... diff --git a/mypy/typeshed/stdlib/http/__init__.pyi b/mypy/typeshed/stdlib/http/__init__.pyi index 822cc0932939..10c1d5926e84 100644 --- a/mypy/typeshed/stdlib/http/__init__.pyi +++ b/mypy/typeshed/stdlib/http/__init__.pyi @@ -2,7 +2,13 @@ import sys from enum import IntEnum from typing_extensions import Literal -__all__ = ["HTTPStatus"] +if sys.version_info >= (3, 11): + from enum import StrEnum + +if sys.version_info >= (3, 11): + __all__ = ["HTTPStatus", "HTTPMethod"] +else: + __all__ = ["HTTPStatus"] class HTTPStatus(IntEnum): @property @@ -74,3 +80,17 @@ class HTTPStatus(IntEnum): EARLY_HINTS: Literal[103] IM_A_TEAPOT: Literal[418] TOO_EARLY: Literal[425] + +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 diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 7ca9c9bb3fc4..38d928f43c9a 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -1,3 +1,4 @@ +import dis import enum import sys import types @@ -459,20 +460,64 @@ def unwrap(func: Callable[..., Any], *, stop: Callable[[Any], Any] | None = ...) # The interpreter stack # -class Traceback(NamedTuple): - filename: str - lineno: int - function: str - code_context: list[str] | None - index: int | None # type: ignore[assignment] - -class FrameInfo(NamedTuple): - frame: FrameType - filename: str - lineno: int - function: str - code_context: list[str] | None - index: int | None # type: ignore[assignment] +if sys.version_info >= (3, 11): + class _Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class Traceback(_Traceback): + positions: dis.Positions | None + def __new__( + cls: type[Self], + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = ..., + ) -> Self: ... + + class _FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class FrameInfo(_FrameInfo): + positions: dis.Positions | None + def __new__( + cls: type[Self], + frame: FrameType, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = ..., + ) -> Self: ... + +else: + class Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... def getouterframes(frame: Any, context: int = ...) -> list[FrameInfo]: ... diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index edb15061a588..6ad4cd4f94e7 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -408,7 +408,7 @@ class LogRecord: ) -> None: ... def getMessage(self) -> str: ... -_L = TypeVar("_L", Logger, LoggerAdapter[Logger], LoggerAdapter[Any]) +_L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) class LoggerAdapter(Generic[_L]): logger: _L diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index 234660cc4f80..b8d5ddda0f35 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -76,9 +76,21 @@ class Server: def accept_connection(self, c: Connection, name: str) -> None: ... class BaseManager: - def __init__( - self, address: Any | None = ..., authkey: bytes | None = ..., serializer: str = ..., ctx: BaseContext | None = ... - ) -> None: ... + if sys.version_info >= (3, 11): + def __init__( + self, + address: Any | None = ..., + authkey: bytes | None = ..., + serializer: str = ..., + ctx: BaseContext | None = ..., + *, + shutdown_timeout: float = ..., + ) -> None: ... + else: + def __init__( + self, address: Any | None = ..., authkey: bytes | None = ..., serializer: str = ..., ctx: BaseContext | None = ... + ) -> None: ... + def get_server(self) -> Server: ... def connect(self) -> None: ... def start(self, initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 76c114591d32..2310de701d54 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -605,6 +605,10 @@ def fstat(fd: int) -> stat_result: ... def ftruncate(__fd: int, __length: int) -> None: ... def fsync(fd: FileDescriptorLike) -> None: ... def isatty(__fd: int) -> bool: ... + +if sys.platform != "win32" and sys.version_info >= (3, 11): + def login_tty(__fd: int) -> None: ... + def lseek(__fd: int, __position: int, __how: int) -> int: ... def open(path: StrOrBytesPath, flags: int, mode: int = ..., *, dir_fd: int | None = ...) -> int: ... def pipe() -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 5dba5b36e3d2..e248db397ab8 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -269,6 +269,9 @@ if sys.platform != "win32": if sys.version_info >= (3, 10): from os import RWF_APPEND as RWF_APPEND + if sys.version_info >= (3, 11): + from os import login_tty as login_tty + if sys.version_info >= (3, 9): from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index ff2a55fb4e61..2f4f3a3a0ed4 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -1,6 +1,7 @@ import enum import sre_compile import sys +from _typeshed import ReadableBuffer from collections.abc import Callable, Iterator from sre_constants import error as error from typing import Any, AnyStr, overload @@ -155,70 +156,67 @@ if sys.version_info < (3, 7): # undocumented _pattern_type: type -# Type-wise these overloads are unnecessary, they could also be modeled using +# Type-wise the compile() overloads are unnecessary, they could also be modeled using # unions in the parameter types. However mypy has a bug regarding TypeVar # constraints (https://github.com/python/mypy/issues/11880), # which limits us here because AnyStr is a constrained TypeVar. +# pattern arguments do *not* accept arbitrary buffers such as bytearray, +# because the pattern must be hashable. @overload def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... @overload def compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... @overload -def search(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def search(pattern: str | Pattern[str], string: str, flags: _FlagsType = ...) -> Match[str] | None: ... @overload -def search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def search(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = ...) -> Match[bytes] | None: ... @overload -def match(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def match(pattern: str | Pattern[str], string: str, flags: _FlagsType = ...) -> Match[str] | None: ... @overload -def match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = ...) -> Match[bytes] | None: ... @overload -def fullmatch(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = ...) -> Match[str] | None: ... @overload -def fullmatch(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Match[AnyStr] | None: ... +def fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = ...) -> Match[bytes] | None: ... @overload -def split(pattern: AnyStr, string: AnyStr, maxsplit: int = ..., flags: _FlagsType = ...) -> list[AnyStr | Any]: ... +def split(pattern: str | Pattern[str], string: str, maxsplit: int = ..., flags: _FlagsType = ...) -> list[str | Any]: ... @overload -def split(pattern: Pattern[AnyStr], string: AnyStr, maxsplit: int = ..., flags: _FlagsType = ...) -> list[AnyStr | Any]: ... +def split( + pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = ..., flags: _FlagsType = ... +) -> list[bytes | Any]: ... @overload -def findall(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> list[Any]: ... +def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = ...) -> list[Any]: ... @overload -def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> list[Any]: ... - -# Return an iterator yielding match objects over all non-overlapping matches -# for the RE pattern in string. The string is scanned left-to-right, and -# matches are returned in the order found. Empty matches are included in the -# result unless they touch the beginning of another match. -@overload -def finditer(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... +def findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = ...) -> list[Any]: ... @overload -def finditer(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... +def finditer(pattern: str | Pattern[str], string: str, flags: _FlagsType = ...) -> Iterator[Match[str]]: ... @overload -def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... +def finditer(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = ...) -> Iterator[Match[bytes]]: ... @overload def sub( - pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> AnyStr: ... -@overload -def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... + pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ..., flags: _FlagsType = ... +) -> str: ... @overload def sub( - pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> AnyStr: ... -@overload -def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> tuple[AnyStr, int]: ... -@overload -def subn( - pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> tuple[AnyStr, int]: ... + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = ..., + flags: _FlagsType = ..., +) -> bytes: ... @overload def subn( - pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> tuple[AnyStr, int]: ... + pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ..., flags: _FlagsType = ... +) -> tuple[str, int]: ... @overload def subn( - pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: _FlagsType = ... -) -> tuple[AnyStr, int]: ... + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = ..., + flags: _FlagsType = ..., +) -> tuple[bytes, int]: ... def escape(pattern: AnyStr) -> AnyStr: ... def purge() -> None: ... def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 7801940f8564..4f8ec07ccc95 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -366,6 +366,8 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): ) if sys.platform == "linux" and sys.version_info >= (3, 10): from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP +if sys.platform == "linux" and sys.version_info >= (3, 11): + from _socket import SO_INCOMING_CPU as SO_INCOMING_CPU if sys.platform == "win32": from _socket import ( RCVALL_IPLEVEL as RCVALL_IPLEVEL, @@ -605,11 +607,22 @@ class SocketIO(RawIOBase): def mode(self) -> Literal["rb", "wb", "rwb"]: ... def getfqdn(name: str = ...) -> str: ... -def create_connection( - address: tuple[str | None, int], - timeout: float | None = ..., # noqa: F811 - source_address: tuple[bytearray | bytes | str, int] | None = ..., -) -> socket: ... + +if sys.version_info >= (3, 11): + def create_connection( + address: tuple[str | None, int], + timeout: float | None = ..., # noqa: F811 + source_address: tuple[bytearray | bytes | str, int] | None = ..., + *, + all_errors: bool = ..., + ) -> socket: ... + +else: + def create_connection( + address: tuple[str | None, int], + timeout: float | None = ..., # noqa: F811 + source_address: tuple[bytearray | bytes | str, int] | None = ..., + ) -> socket: ... if sys.version_info >= (3, 8): def has_dualstack_ipv6() -> bool: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 87e843c5fb26..a6ccc9977c1c 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -460,3 +460,5 @@ if sys.version_info >= (3, 11): def __len__(self) -> int: ... def __enter__(self: Self) -> Self: ... def __exit__(self, __typ: object, __val: object, __tb: object) -> Literal[False]: ... + def __getitem__(self, __item: SupportsIndex | slice) -> int: ... + def __setitem__(self, __item: SupportsIndex | slice, __value: int) -> None: ... diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 98bbf7d33f90..83178e15d9e8 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -118,6 +118,12 @@ else: _T = TypeVar("_T") +# These two are private but documented +if sys.version_info >= (3, 11): + _USE_VFORK: bool +if sys.version_info >= (3, 8): + _USE_POSIX_SPAWN: bool + class CompletedProcess(Generic[_T]): # morally: _CMD args: Any @@ -792,13 +798,562 @@ class Popen(Generic[AnyStr]): stdout: IO[AnyStr] | None stderr: IO[AnyStr] | None pid: int - returncode: int + returncode: int | Any universal_newlines: bool # Technically it is wrong that Popen provides __new__ instead of __init__ # but this shouldn't come up hopefully? - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): + # process_group is added in 3.11 + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str, + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + process_group: int | None = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str | None = ..., + errors: str, + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + process_group: int | None = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + text: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + process_group: int | None = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[True], + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + process_group: int | None = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[None, False] = ..., + encoding: None = ..., + errors: None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + process_group: int | None = ..., + ) -> Popen[bytes]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + process_group: int | None = ..., + ) -> Popen[Any]: ... + elif sys.version_info >= (3, 10): + # pipesize is added in 3.10 + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str, + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str | None = ..., + errors: str, + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + text: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[True], + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[None, False] = ..., + encoding: None = ..., + errors: None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + ) -> Popen[bytes]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + pipesize: int = ..., + ) -> Popen[Any]: ... + elif sys.version_info >= (3, 9): + # user, group, extra_groups, umask were added in 3.9 + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str, + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str | None = ..., + errors: str, + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + *, + universal_newlines: Literal[True], + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + # where the *real* keyword only args start + text: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[True], + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + ) -> Popen[str]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: Literal[False] = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: Literal[None, False] = ..., + encoding: None = ..., + errors: None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + ) -> Popen[bytes]: ... + @overload + def __new__( + cls, + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE | None = ..., + stdout: _FILE | None = ..., + stderr: _FILE | None = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any | None = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + text: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + user: str | int | None = ..., + group: str | int | None = ..., + extra_groups: Iterable[str | int] | None = ..., + umask: int = ..., + ) -> Popen[Any]: ... + elif sys.version_info >= (3, 7): # text is added in 3.7 @overload def __new__( diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 92b806e04420..4e24cbd167d9 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -122,6 +122,9 @@ class _flags(_uninstantiable_structseq, _FlagTuple): if sys.version_info >= (3, 10): @property def warn_default_encoding(self) -> int: ... # undocumented + if sys.version_info >= (3, 11): + @property + def safe_path(self) -> bool: ... float_info: _float_info @@ -320,9 +323,8 @@ class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHo def get_asyncgen_hooks() -> _asyncgen_hooks: ... def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... -if sys.version_info >= (3, 6): - if sys.platform == "win32": - def _enablelegacywindowsfsencoding() -> None: ... +if sys.platform == "win32": + def _enablelegacywindowsfsencoding() -> None: ... if sys.version_info >= (3, 7): def get_coroutine_origin_tracking_depth() -> int: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 66c52107067d..582503971e15 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -6,7 +6,7 @@ from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Generic, Protocol, TypeVar, Union, overload +from typing import Any, Generic, NamedTuple, Protocol, TypeVar, Union, overload from typing_extensions import Literal, TypeAlias, TypedDict if sys.version_info >= (3, 9): @@ -198,6 +198,14 @@ _ScreenUnits: TypeAlias = str | float # Often the right type instead of int. Ma _XYScrollCommand: TypeAlias = str | Callable[[float, float], Any] # -xscrollcommand and -yscrollcommand in 'options' manual page _TakeFocusValue: TypeAlias = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' +if sys.version_info >= (3, 11): + class _VersionInfoType(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + class EventType(str, Enum): Activate: str ButtonPress: str @@ -377,6 +385,9 @@ class Misc: def lower(self, belowThis: Any | None = ...) -> None: ... def tkraise(self, aboveThis: Any | None = ...) -> None: ... lift = tkraise + if sys.version_info >= (3, 11): + def info_patchlevel(self) -> _VersionInfoType: ... + def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = ...) -> int: ... def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = ...) -> str: ... def winfo_cells(self) -> int: ... @@ -475,6 +486,8 @@ class Misc: def unbind_class(self, className: str, sequence: str) -> None: ... def mainloop(self, n: int = ...) -> None: ... def quit(self) -> None: ... + @property + def _windowingsystem(self) -> Literal["win32", "aqua", "x11"]: ... def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: ... def register( self, func: Callable[..., Any], subst: Callable[..., Sequence[Any]] | None = ..., needcleanup: int = ... @@ -1221,8 +1234,9 @@ class Canvas(Widget, XView, YView): def coords(self, __tagOrId: str | _CanvasItemId, __args: list[int] | list[float] | tuple[float, ...]) -> None: ... @overload def coords(self, __tagOrId: str | _CanvasItemId, __x1: float, __y1: float, *args: float) -> None: ... - # create_foo() methods accept coords as a list, a tuple, or as separate arguments. - # Keyword arguments should be the same in each pair of overloads. + # create_foo() methods accept coords as a list or tuple, or as separate arguments. + # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)]. + # Keyword arguments should be the same in all overloads of each method. def create_arc(self, *args, **kw) -> _CanvasItemId: ... def create_bitmap(self, *args, **kw) -> _CanvasItemId: ... def create_image(self, *args, **kw) -> _CanvasItemId: ... @@ -1260,7 +1274,43 @@ class Canvas(Widget, XView, YView): @overload def create_line( self, - __coords: tuple[float, float, float, float] | list[int] | list[float], + __xy_pair_0: tuple[float, float], + __xy_pair_1: tuple[float, float], + *, + activedash: str | list[int] | tuple[int, ...] = ..., + activefill: _Color = ..., + activestipple: str = ..., + activewidth: _ScreenUnits = ..., + arrow: Literal["first", "last", "both"] = ..., + arrowshape: tuple[float, float, float] = ..., + capstyle: Literal["round", "projecting", "butt"] = ..., + dash: str | list[int] | tuple[int, ...] = ..., + dashoffset: _ScreenUnits = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., + disabledfill: _Color = ..., + disabledstipple: _Bitmap = ..., + disabledwidth: _ScreenUnits = ..., + fill: _Color = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: _ScreenUnits = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "active", "disabled"] = ..., + stipple: _Bitmap = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: _ScreenUnits = ..., + ) -> _CanvasItemId: ... + @overload + def create_line( + self, + __coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), *, activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., @@ -1320,7 +1370,44 @@ class Canvas(Widget, XView, YView): @overload def create_oval( self, - __coords: tuple[float, float, float, float] | list[int] | list[float], + __xy_pair_0: tuple[float, float], + __xy_pair_1: tuple[float, float], + *, + activedash: str | list[int] | tuple[int, ...] = ..., + activefill: _Color = ..., + activeoutline: _Color = ..., + activeoutlinestipple: _Color = ..., + activestipple: str = ..., + activewidth: _ScreenUnits = ..., + dash: str | list[int] | tuple[int, ...] = ..., + dashoffset: _ScreenUnits = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., + disabledfill: _Color = ..., + disabledoutline: _Color = ..., + disabledoutlinestipple: _Color = ..., + disabledstipple: _Bitmap = ..., + disabledwidth: _ScreenUnits = ..., + fill: _Color = ..., + offset: _ScreenUnits = ..., + outline: _Color = ..., + outlineoffset: _ScreenUnits = ..., + outlinestipple: _Bitmap = ..., + state: Literal["normal", "active", "disabled"] = ..., + stipple: _Bitmap = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: _ScreenUnits = ..., + ) -> _CanvasItemId: ... + @overload + def create_oval( + self, + __coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), *, activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., @@ -1384,7 +1471,47 @@ class Canvas(Widget, XView, YView): @overload def create_polygon( self, - __coords: tuple[float, ...] | list[int] | list[float], + __xy_pair_0: tuple[float, float], + __xy_pair_1: tuple[float, float], + *xy_pairs: tuple[float, float], + activedash: str | list[int] | tuple[int, ...] = ..., + activefill: _Color = ..., + activeoutline: _Color = ..., + activeoutlinestipple: _Color = ..., + activestipple: str = ..., + activewidth: _ScreenUnits = ..., + dash: str | list[int] | tuple[int, ...] = ..., + dashoffset: _ScreenUnits = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., + disabledfill: _Color = ..., + disabledoutline: _Color = ..., + disabledoutlinestipple: _Color = ..., + disabledstipple: _Bitmap = ..., + disabledwidth: _ScreenUnits = ..., + fill: _Color = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: _ScreenUnits = ..., + outline: _Color = ..., + outlineoffset: _ScreenUnits = ..., + outlinestipple: _Bitmap = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "active", "disabled"] = ..., + stipple: _Bitmap = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: _ScreenUnits = ..., + ) -> _CanvasItemId: ... + @overload + def create_polygon( + self, + __coords: ( + tuple[float, ...] + | tuple[tuple[float, float], ...] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), *, activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., @@ -1448,7 +1575,44 @@ class Canvas(Widget, XView, YView): @overload def create_rectangle( self, - __coords: tuple[float, float, float, float] | list[int] | list[float], + __xy_pair_0: tuple[float, float], + __xy_pair_1: tuple[float, float], + *, + activedash: str | list[int] | tuple[int, ...] = ..., + activefill: _Color = ..., + activeoutline: _Color = ..., + activeoutlinestipple: _Color = ..., + activestipple: str = ..., + activewidth: _ScreenUnits = ..., + dash: str | list[int] | tuple[int, ...] = ..., + dashoffset: _ScreenUnits = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., + disabledfill: _Color = ..., + disabledoutline: _Color = ..., + disabledoutlinestipple: _Color = ..., + disabledstipple: _Bitmap = ..., + disabledwidth: _ScreenUnits = ..., + fill: _Color = ..., + offset: _ScreenUnits = ..., + outline: _Color = ..., + outlineoffset: _ScreenUnits = ..., + outlinestipple: _Bitmap = ..., + state: Literal["normal", "active", "disabled"] = ..., + stipple: _Bitmap = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: _ScreenUnits = ..., + ) -> _CanvasItemId: ... + @overload + def create_rectangle( + self, + __coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), *, activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 872ed57a7c76..ed2476e44a86 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -651,6 +651,10 @@ if sys.version_info >= (3, 9): @property def __parameters__(self) -> tuple[Any, ...]: ... def __init__(self, origin: type, args: Any) -> None: ... + if sys.version_info >= (3, 11): + @property + def __unpacked__(self) -> bool: ... + def __getattr__(self, name: str) -> Any: ... # incomplete if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 28b588d79c9b..37ea55c9f2ef 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,6 +1,6 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys -from _typeshed import Self as TypeshedSelf, SupportsKeysAndGetItem +from _typeshed import ReadableBuffer, Self as TypeshedSelf, SupportsKeysAndGetItem from abc import ABCMeta, abstractmethod from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final @@ -88,6 +88,7 @@ if sys.version_info >= (3, 11): "assert_type", "cast", "clear_overloads", + "dataclass_transform", "final", "get_args", "get_origin", @@ -1079,7 +1080,10 @@ class Match(Generic[AnyStr]): # this match instance. @property def re(self) -> Pattern[AnyStr]: ... - def expand(self, template: AnyStr) -> AnyStr: ... + @overload + def expand(self: Match[str], template: str) -> str: ... + @overload + def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload def group(self, __group: _Literal[0] = ...) -> AnyStr: ... @@ -1124,20 +1128,49 @@ class Pattern(Generic[AnyStr]): def groups(self) -> int: ... @property def pattern(self) -> AnyStr: ... - def search(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def match(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def fullmatch(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr | Any]: ... - def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ... - def finditer(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Iterator[Match[AnyStr]]: ... @overload - def sub(self, repl: AnyStr, string: AnyStr, count: int = ...) -> AnyStr: ... + def search(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... + @overload + def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... + @overload + def match(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... + @overload + def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... + @overload + def fullmatch(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... + @overload + def fullmatch(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... + @overload + def split(self: Pattern[str], string: str, maxsplit: int = ...) -> list[str | Any]: ... + @overload + def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = ...) -> list[bytes | Any]: ... + # return type depends on the number of groups in the pattern + @overload + def findall(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> list[Any]: ... + @overload + def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> list[Any]: ... + @overload + def finditer(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Iterator[Match[str]]: ... + @overload + def finditer(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Iterator[Match[bytes]]: ... + @overload + def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ...) -> str: ... @overload - def sub(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ...) -> AnyStr: ... + def sub( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = ..., + ) -> bytes: ... @overload - def subn(self, repl: AnyStr, string: AnyStr, count: int = ...) -> tuple[AnyStr, int]: ... + def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ...) -> tuple[str, int]: ... @overload - def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ...) -> tuple[AnyStr, int]: ... + def subn( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = ..., + ) -> tuple[bytes, int]: ... def __copy__(self) -> Pattern[AnyStr]: ... def __deepcopy__(self, __memo: Any) -> Pattern[AnyStr]: ... if sys.version_info >= (3, 9): @@ -1192,6 +1225,14 @@ if sys.version_info >= (3, 11): def assert_type(__val: _T, __typ: Any) -> _T: ... def clear_overloads() -> None: ... def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... + def dataclass_transform( + *, + eq_default: bool = ..., + order_default: bool = ..., + kw_only_default: bool = ..., + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., + **kwargs: Any, + ) -> Callable[[_T], _T]: ... # Type constructors diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 1c75ec38e75c..b94daaba9f49 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,7 +1,7 @@ import abc import sys from _typeshed import Self as TypeshedSelf # see #6932 for why the alias cannot have a leading underscore -from typing import ( # noqa: Y022,Y027 +from typing import ( # noqa: Y022,Y027,Y039 TYPE_CHECKING as TYPE_CHECKING, Any, AsyncContextManager as AsyncContextManager, @@ -201,6 +201,7 @@ if sys.version_info >= (3, 11): assert_never as assert_never, assert_type as assert_type, clear_overloads as clear_overloads, + dataclass_transform as dataclass_transform, get_overloads as get_overloads, reveal_type as reveal_type, ) @@ -224,12 +225,11 @@ else: def __init__(self, name: str) -> None: ... def __iter__(self) -> Any: ... # Unpack[Self] -# Experimental (hopefully these will be in 3.11) -def dataclass_transform( - *, - eq_default: bool = ..., - order_default: bool = ..., - kw_only_default: bool = ..., - field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., - **kwargs: object, -) -> Callable[[_T], _T]: ... + def dataclass_transform( + *, + eq_default: bool = ..., + order_default: bool = ..., + kw_only_default: bool = ..., + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., + **kwargs: object, + ) -> Callable[[_T], _T]: ... diff --git a/mypy/typeshed/stdlib/urllib/error.pyi b/mypy/typeshed/stdlib/urllib/error.pyi index 48c8287e979a..7a4de10d7cf6 100644 --- a/mypy/typeshed/stdlib/urllib/error.pyi +++ b/mypy/typeshed/stdlib/urllib/error.pyi @@ -9,6 +9,8 @@ class URLError(IOError): def __init__(self, reason: str | BaseException, filename: str | None = ...) -> None: ... class HTTPError(URLError, addinfourl): + @property + def headers(self) -> Message: ... # type: ignore[override] @property def reason(self) -> str: ... # type: ignore[override] code: int diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index bd7afb2d7cba..c9c143991e3a 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,3 +1,4 @@ +import sys from _warnings import warn as warn, warn_explicit as warn_explicit from collections.abc import Sequence from types import ModuleType, TracebackType @@ -56,12 +57,48 @@ class WarningMessage: ) -> None: ... class catch_warnings: - @overload - def __new__(cls, *, record: Literal[False] = ..., module: ModuleType | None = ...) -> _catch_warnings_without_records: ... - @overload - def __new__(cls, *, record: Literal[True], module: ModuleType | None = ...) -> _catch_warnings_with_records: ... - @overload - def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... + if sys.version_info >= (3, 11): + @overload + def __new__( + cls, + *, + record: Literal[False] = ..., + module: ModuleType | None = ..., + action: _ActionKind | None = ..., + category: type[Warning] = ..., + lineno: int = ..., + append: bool = ..., + ) -> _catch_warnings_without_records: ... + @overload + def __new__( + cls, + *, + record: Literal[True], + module: ModuleType | None = ..., + action: _ActionKind | None = ..., + category: type[Warning] = ..., + lineno: int = ..., + append: bool = ..., + ) -> _catch_warnings_with_records: ... + @overload + def __new__( + cls, + *, + record: bool, + module: ModuleType | None = ..., + action: _ActionKind | None = ..., + category: type[Warning] = ..., + lineno: int = ..., + append: bool = ..., + ) -> catch_warnings: ... + else: + @overload + def __new__(cls, *, record: Literal[False] = ..., module: ModuleType | None = ...) -> _catch_warnings_without_records: ... + @overload + def __new__(cls, *, record: Literal[True], module: ModuleType | None = ...) -> _catch_warnings_with_records: ... + @overload + def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... + def __enter__(self) -> list[WarningMessage] | None: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 414530b0a34c..dacb6fffcc6b 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -319,7 +319,7 @@ def iterparse( class XMLPullParser: def __init__(self, events: Sequence[str] | None = ..., *, _parser: XMLParser | None = ...) -> None: ... - def feed(self, data: bytes) -> None: ... + def feed(self, data: str | bytes) -> None: ... def close(self) -> None: ... def read_events(self) -> Iterator[tuple[str, Element]]: ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index d5255b15c3c0..276f8df82a6d 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -222,6 +222,8 @@ class ZipFile: ) -> None: ... else: def writestr(self, zinfo_or_arcname: str | ZipInfo, data: bytes | str, compress_type: int | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def mkdir(self, zinfo_or_directory: str | ZipInfo, mode: int = ...) -> None: ... class PyZipFile(ZipFile): def __init__( diff --git a/mypy/typeshed/stubs/mypy-extensions/METADATA.toml b/mypy/typeshed/stubs/mypy-extensions/METADATA.toml index 79b51931ee0b..582104d3a1a7 100644 --- a/mypy/typeshed/stubs/mypy-extensions/METADATA.toml +++ b/mypy/typeshed/stubs/mypy-extensions/METADATA.toml @@ -1,2 +1 @@ version = "0.4.*" -python2 = true diff --git a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index 33b47244d385..412c3cb15142 100644 --- a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,7 +1,7 @@ import abc -import sys from _typeshed import Self -from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, TypeVar, ValuesView +from collections.abc import Callable, ItemsView, KeysView, Mapping, ValuesView +from typing import Any, Generic, TypeVar _T = TypeVar("_T") _U = TypeVar("_U") @@ -15,16 +15,9 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore def update(self: Self, __m: Self) -> None: ... - if sys.version_info >= (3, 0): - def items(self) -> ItemsView[str, object]: ... - def keys(self) -> KeysView[str]: ... - def values(self) -> ValuesView[object]: ... - else: - def has_key(self, k: str) -> bool: ... - def viewitems(self) -> ItemsView[str, object]: ... - def viewkeys(self) -> KeysView[str]: ... - def viewvalues(self) -> ValuesView[object]: ... - + def items(self) -> ItemsView[str, object]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[object]: ... def __delitem__(self, k: NoReturn) -> None: ... def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... From c49aeccf39dffaf0c137f395844f1ab84f3b4849 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Wed, 11 May 2022 01:01:21 -0700 Subject: [PATCH 2/3] Sync typeshed Source commit: https://github.com/python/typeshed/commit/a27f15ef0eb12b961d0fb58f8615a3df901a9176 --- mypy/typeshed/stdlib/builtins.pyi | 8 ++++---- mypy/typeshed/stdlib/statistics.pyi | 8 +++++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 9e04ac4e50a3..d3d34c72fcfc 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -250,10 +250,6 @@ class int: def __rmod__(self, __x: int) -> int: ... def __rdivmod__(self, __x: int) -> tuple[int, int]: ... @overload - def __pow__(self, __x: int, __modulo: Literal[0]) -> NoReturn: ... - @overload - def __pow__(self, __x: int, __modulo: int) -> int: ... - @overload def __pow__(self, __x: Literal[0]) -> Literal[1]: ... @overload def __pow__(self, __x: Literal[0], __modulo: None) -> Literal[1]: ... @@ -265,6 +261,10 @@ class int: # return type must be Any as `int | float` causes too many false-positive errors @overload def __pow__(self, __x: int, __modulo: None = ...) -> Any: ... + @overload + def __pow__(self, __x: int, __modulo: Literal[0]) -> NoReturn: ... + @overload + def __pow__(self, __x: int, __modulo: int) -> int: ... def __rpow__(self, __x: int, __mod: int | None = ...) -> Any: ... def __and__(self, __n: int) -> int: ... def __or__(self, __n: int) -> int: ... diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 540ccfcaaa8c..e6c3d8f35bc6 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -94,7 +94,13 @@ else: def median(data: Iterable[_NumberT]) -> _NumberT: ... def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... -def median_grouped(data: Iterable[_NumberT], interval: _NumberT = ...) -> _NumberT: ... + +if sys.version_info >= (3, 11): + def median_grouped(data: Iterable[SupportsFloat], interval: SupportsFloat = ...) -> float: ... + +else: + def median_grouped(data: Iterable[_NumberT], interval: _NumberT = ...) -> _NumberT | float: ... + def mode(data: Iterable[_HashableT]) -> _HashableT: ... if sys.version_info >= (3, 8): From 97655f77af2c7caa5602ad76476f39c799eb5dfe Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Wed, 11 May 2022 01:47:33 -0700 Subject: [PATCH 3/3] these tests are fine --- test-data/unit/cmdline.test | 4 ++-- test-data/unit/pythoneval.test | 14 ++++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index a1b4d986b98a..86a975fc4949 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -644,10 +644,10 @@ python_version = 3.6 [file int_pow.py] a = 1 b = a + 2 -reveal_type(a**0) # N: Revealed type is "builtins.int" +reveal_type(a**0) # N: Revealed type is "Literal[1]" reveal_type(a**1) # N: Revealed type is "builtins.int" reveal_type(a**2) # N: Revealed type is "builtins.int" -reveal_type(a**-0) # N: Revealed type is "builtins.int" +reveal_type(a**-0) # N: Revealed type is "Literal[1]" reveal_type(a**-1) # N: Revealed type is "builtins.float" reveal_type(a**(-2)) # N: Revealed type is "builtins.float" reveal_type(a**b) # N: Revealed type is "Any" diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index a3f44fff5e33..b59d50feb986 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -1005,8 +1005,11 @@ re.subn(bpat, b'', b'')[0] + b'' re.subn(bre, lambda m: b'', b'')[0] + b'' re.subn(bpat, lambda m: b'', b'')[0] + b'' [out] -_program.py:7: error: Value of type variable "AnyStr" of "search" cannot be "Sequence[object]" -_program.py:9: error: Cannot infer type argument 1 of "search" +_testReModuleBytes.py:7: error: No overload variant of "search" matches argument types "bytes", "str" +_testReModuleBytes.py:7: note: Possible overload variants: +_testReModuleBytes.py:7: note: def search(pattern: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]] +_testReModuleBytes.py:7: note: def search(pattern: Union[bytes, Pattern[bytes]], string: Union[bytes, Union[bytearray, memoryview, array[Any], mmap, _CData]], flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]] +_testReModuleBytes.py:9: error: Argument 1 to "search" has incompatible type "Pattern[bytes]"; expected "Union[str, Pattern[str]]" [case testReModuleString] # Regression tests for various overloads in the re module -- string version @@ -1029,8 +1032,11 @@ re.subn(spat, '', '')[0] + '' re.subn(sre, lambda m: '', '')[0] + '' re.subn(spat, lambda m: '', '')[0] + '' [out] -_program.py:7: error: Value of type variable "AnyStr" of "search" cannot be "Sequence[object]" -_program.py:9: error: Cannot infer type argument 1 of "search" +_testReModuleString.py:7: error: No overload variant of "search" matches argument types "str", "bytes" +_testReModuleString.py:7: note: Possible overload variants: +_testReModuleString.py:7: note: def search(pattern: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]] +_testReModuleString.py:7: note: def search(pattern: Union[bytes, Pattern[bytes]], string: Union[bytes, Union[bytearray, memoryview, array[Any], mmap, _CData]], flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]] +_testReModuleString.py:9: error: Argument 1 to "search" has incompatible type "Pattern[str]"; expected "Union[bytes, Pattern[bytes]]" [case testListSetitemTuple] from typing import List, Tuple