diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index 869d2e110a66..2983c23d5150 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -1174,7 +1174,7 @@ def test_config_file(self) -> None: output = run_stubtest(stub=stub, runtime=runtime, options=[]) assert remove_color_code(output) == ( "error: test_module.temp variable differs from runtime type Literal[5]\n" - "Stub: at line 2\ndecimal.Decimal\nRuntime:\n5\n\n" + "Stub: at line 2\n_decimal.Decimal\nRuntime:\n5\n\n" ) output = run_stubtest(stub=stub, runtime=runtime, options=[], config_file=config_file) assert output == "" diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index d3ba459dd9e3..eefc7b895436 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -286,6 +286,7 @@ webbrowser: 2.7- winreg: 3.0- winsound: 2.7- wsgiref: 2.7- +wsgiref.types: 3.11- xdrlib: 2.7- xml: 2.7- xmlrpc: 3.0- diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index f801b5deb0d9..cb13c7452081 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -1,13 +1,13 @@ import sys from typing import Any, ClassVar -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias PyCF_ONLY_AST: Literal[1024] if sys.version_info >= (3, 8): PyCF_TYPE_COMMENTS: Literal[4096] PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] -_identifier = str +_identifier: TypeAlias = str class AST: if sys.version_info >= (3, 10): @@ -172,6 +172,14 @@ class Try(stmt): orelse: list[stmt] finalbody: list[stmt] +if sys.version_info >= (3, 11): + class TryStar(stmt): + __match_args__ = ("body", "handlers", "orelse", "finalbody") + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] + finalbody: list[stmt] + class Assert(stmt): if sys.version_info >= (3, 10): __match_args__ = ("test", "msg") @@ -358,10 +366,10 @@ class Attribute(expr): ctx: expr_context if sys.version_info >= (3, 9): - _SliceT = expr + _SliceT: TypeAlias = expr else: class slice(AST): ... - _SliceT = slice + _SliceT: TypeAlias = slice class Slice(_SliceT): if sys.version_info >= (3, 10): @@ -516,7 +524,7 @@ if sys.version_info >= (3, 10): class pattern(AST): ... # Without the alias, Pyright complains variables named pattern are recursively defined - _pattern = pattern + _pattern: TypeAlias = pattern class match_case(AST): __match_args__ = ("pattern", "guard", "body") diff --git a/mypy/typeshed/stdlib/_bisect.pyi b/mypy/typeshed/stdlib/_bisect.pyi index 5608094ccbd6..d902e1eea7d4 100644 --- a/mypy/typeshed/stdlib/_bisect.pyi +++ b/mypy/typeshed/stdlib/_bisect.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import SupportsRichComparisonT -from typing import Callable, MutableSequence, Sequence, TypeVar, overload +from collections.abc import Callable, MutableSequence, Sequence +from typing import TypeVar, overload _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 1781a2418ca0..e335f6d5119a 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -1,13 +1,15 @@ import codecs import sys -from typing import Any, Callable +from collections.abc import Callable +from typing import Any +from typing_extensions import TypeAlias # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap: def size(self) -> int: ... -_MapT = dict[int, int] | _EncodingMap -_Handler = Callable[[Exception], tuple[str, int]] +_MapT: TypeAlias = dict[int, int] | _EncodingMap +_Handler: TypeAlias = Callable[[Exception], tuple[str, int]] def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str, __handler: _Handler) -> None: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index bd8d35641b37..8373fe836330 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -1,6 +1,6 @@ import sys from types import MappingProxyType -from typing import ( +from typing import ( # noqa: Y027,Y038 AbstractSet as Set, AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index e71f7d14bd2b..ec3c7fe70856 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -1,6 +1,7 @@ from _typeshed import WriteableBuffer +from collections.abc import Callable from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase -from typing import Any, Callable, Protocol +from typing import Any, Protocol BUFFER_SIZE = DEFAULT_BUFFER_SIZE diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index 161a89778de8..ae9031df6e81 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -1,5 +1,6 @@ -from typing import Any, Iterable, Iterator, Protocol, Union -from typing_extensions import Literal +from collections.abc import Iterable, Iterator +from typing import Any, Protocol, Union +from typing_extensions import Literal, TypeAlias __version__: str @@ -21,7 +22,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, type[Dialect]] +_DialectLike: TypeAlias = Union[str, Dialect, type[Dialect]] class _reader(Iterator[list[str]]): dialect: Dialect diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index e193759bdc6e..95a128a32256 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import SupportsRead from typing import IO, Any, NamedTuple, overload -from typing_extensions import final +from typing_extensions import TypeAlias, final if sys.platform != "win32": - _chtype = str | bytes | int + _chtype: TypeAlias = str | bytes | int # ACS codes are only initialized after initscr is called ACS_BBSS: int diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index de49a787283d..fdeca8f7c42f 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -1,3 +1,265 @@ -from decimal import * +import numbers +import sys +from _typeshed import Self +from collections.abc import Container, Sequence +from types import TracebackType +from typing import Any, NamedTuple, Union, overload +from typing_extensions import TypeAlias +_Decimal: TypeAlias = Decimal | int +_DecimalNew: TypeAlias = Union[Decimal, float, str, tuple[int, Sequence[int], int]] +_ComparableNum: TypeAlias = Decimal | float | numbers.Rational + +__version__: str __libmpdec_version__: str + +class DecimalTuple(NamedTuple): + sign: int + digits: tuple[int, ...] + exponent: int + +ROUND_DOWN: str +ROUND_HALF_UP: str +ROUND_HALF_EVEN: str +ROUND_CEILING: str +ROUND_FLOOR: str +ROUND_UP: str +ROUND_HALF_DOWN: str +ROUND_05UP: str + +if sys.version_info >= (3, 7): + HAVE_CONTEXTVAR: bool +HAVE_THREADS: bool +MAX_EMAX: int +MAX_PREC: int +MIN_EMIN: int +MIN_ETINY: int + +class DecimalException(ArithmeticError): ... +class Clamped(DecimalException): ... +class InvalidOperation(DecimalException): ... +class ConversionSyntax(InvalidOperation): ... +class DivisionByZero(DecimalException, ZeroDivisionError): ... +class DivisionImpossible(InvalidOperation): ... +class DivisionUndefined(InvalidOperation, ZeroDivisionError): ... +class Inexact(DecimalException): ... +class InvalidContext(InvalidOperation): ... +class Rounded(DecimalException): ... +class Subnormal(DecimalException): ... +class Overflow(Inexact, Rounded): ... +class Underflow(Inexact, Rounded, Subnormal): ... +class FloatOperation(DecimalException, TypeError): ... + +def setcontext(__context: Context) -> None: ... +def getcontext() -> Context: ... +def localcontext(ctx: Context | None = ...) -> _ContextManager: ... + +class Decimal: + def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... + @classmethod + def from_float(cls: type[Self], __f: float) -> Self: ... + def __bool__(self) -> bool: ... + def compare(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def __hash__(self) -> int: ... + def as_tuple(self) -> DecimalTuple: ... + def as_integer_ratio(self) -> tuple[int, int]: ... + def to_eng_string(self, context: Context | None = ...) -> str: ... + def __abs__(self) -> Decimal: ... + def __add__(self, __other: _Decimal) -> Decimal: ... + def __divmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... + def __eq__(self, __other: object) -> bool: ... + def __floordiv__(self, __other: _Decimal) -> Decimal: ... + def __ge__(self, __other: _ComparableNum) -> bool: ... + def __gt__(self, __other: _ComparableNum) -> bool: ... + def __le__(self, __other: _ComparableNum) -> bool: ... + def __lt__(self, __other: _ComparableNum) -> bool: ... + def __mod__(self, __other: _Decimal) -> Decimal: ... + def __mul__(self, __other: _Decimal) -> Decimal: ... + def __neg__(self) -> Decimal: ... + def __pos__(self) -> Decimal: ... + def __pow__(self, __other: _Decimal, __modulo: _Decimal | None = ...) -> Decimal: ... + def __radd__(self, __other: _Decimal) -> Decimal: ... + def __rdivmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, __other: _Decimal) -> Decimal: ... + def __rmod__(self, __other: _Decimal) -> Decimal: ... + def __rmul__(self, __other: _Decimal) -> Decimal: ... + def __rsub__(self, __other: _Decimal) -> Decimal: ... + def __rtruediv__(self, __other: _Decimal) -> Decimal: ... + def __sub__(self, __other: _Decimal) -> Decimal: ... + def __truediv__(self, __other: _Decimal) -> Decimal: ... + def remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __trunc__(self) -> int: ... + @property + def real(self) -> Decimal: ... + @property + def imag(self) -> Decimal: ... + def conjugate(self) -> Decimal: ... + def __complex__(self) -> complex: ... + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, __ndigits: int) -> Decimal: ... + def __floor__(self) -> int: ... + def __ceil__(self) -> int: ... + def fma(self, other: _Decimal, third: _Decimal, context: Context | None = ...) -> Decimal: ... + def __rpow__(self, __other: _Decimal, __context: Context | None = ...) -> Decimal: ... + def normalize(self, context: Context | None = ...) -> Decimal: ... + def quantize(self, exp: _Decimal, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... + def same_quantum(self, other: _Decimal, context: Context | None = ...) -> bool: ... + def to_integral_exact(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... + def to_integral_value(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... + def to_integral(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... + def sqrt(self, context: Context | None = ...) -> Decimal: ... + def max(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def min(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def adjusted(self) -> int: ... + def canonical(self) -> Decimal: ... + def compare_signal(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def compare_total(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def compare_total_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def copy_abs(self) -> Decimal: ... + def copy_negate(self) -> Decimal: ... + def copy_sign(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def exp(self, context: Context | None = ...) -> Decimal: ... + def is_canonical(self) -> bool: ... + def is_finite(self) -> bool: ... + def is_infinite(self) -> bool: ... + def is_nan(self) -> bool: ... + def is_normal(self, context: Context | None = ...) -> bool: ... + def is_qnan(self) -> bool: ... + def is_signed(self) -> bool: ... + def is_snan(self) -> bool: ... + def is_subnormal(self, context: Context | None = ...) -> bool: ... + def is_zero(self) -> bool: ... + def ln(self, context: Context | None = ...) -> Decimal: ... + def log10(self, context: Context | None = ...) -> Decimal: ... + def logb(self, context: Context | None = ...) -> Decimal: ... + def logical_and(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def logical_invert(self, context: Context | None = ...) -> Decimal: ... + def logical_or(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def logical_xor(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def max_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def min_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def next_minus(self, context: Context | None = ...) -> Decimal: ... + def next_plus(self, context: Context | None = ...) -> Decimal: ... + def next_toward(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def number_class(self, context: Context | None = ...) -> str: ... + def radix(self) -> Decimal: ... + def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def __reduce__(self: Self) -> tuple[type[Self], tuple[str]]: ... + def __copy__(self: Self) -> Self: ... + def __deepcopy__(self: Self, __memo: Any) -> Self: ... + def __format__(self, __specifier: str, __context: Context | None = ...) -> str: ... + +class _ContextManager: + new_context: Context + saved_context: Context + def __init__(self, new_context: Context) -> None: ... + def __enter__(self) -> Context: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +_TrapType: TypeAlias = type[DecimalException] + +class Context: + prec: int + rounding: str + Emin: int + Emax: int + capitals: int + clamp: int + traps: dict[_TrapType, bool] + flags: dict[_TrapType, bool] + def __init__( + self, + prec: int | None = ..., + rounding: str | None = ..., + Emin: int | None = ..., + Emax: int | None = ..., + capitals: int | None = ..., + clamp: int | None = ..., + flags: None | dict[_TrapType, bool] | Container[_TrapType] = ..., + traps: None | dict[_TrapType, bool] | Container[_TrapType] = ..., + _ignored_flags: list[_TrapType] | None = ..., + ) -> None: ... + # __setattr__() only allows to set a specific set of attributes, + # already defined above. + def __delattr__(self, __name: str) -> None: ... + def __reduce__(self: Self) -> tuple[type[Self], tuple[Any, ...]]: ... + def clear_flags(self) -> None: ... + def clear_traps(self) -> None: ... + def copy(self) -> Context: ... + def __copy__(self) -> Context: ... + __hash__: Any + def Etiny(self) -> int: ... + def Etop(self) -> int: ... + def create_decimal(self, __num: _DecimalNew = ...) -> Decimal: ... + def create_decimal_from_float(self, __f: float) -> Decimal: ... + def abs(self, __x: _Decimal) -> Decimal: ... + def add(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def canonical(self, __x: Decimal) -> Decimal: ... + def compare(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def compare_signal(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def compare_total(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def compare_total_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def copy_abs(self, __x: _Decimal) -> Decimal: ... + def copy_decimal(self, __x: _Decimal) -> Decimal: ... + def copy_negate(self, __x: _Decimal) -> Decimal: ... + def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def divmod(self, __x: _Decimal, __y: _Decimal) -> tuple[Decimal, Decimal]: ... + def exp(self, __x: _Decimal) -> Decimal: ... + def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... + def is_canonical(self, __x: _Decimal) -> bool: ... + def is_finite(self, __x: _Decimal) -> bool: ... + def is_infinite(self, __x: _Decimal) -> bool: ... + def is_nan(self, __x: _Decimal) -> bool: ... + def is_normal(self, __x: _Decimal) -> bool: ... + def is_qnan(self, __x: _Decimal) -> bool: ... + def is_signed(self, __x: _Decimal) -> bool: ... + def is_snan(self, __x: _Decimal) -> bool: ... + def is_subnormal(self, __x: _Decimal) -> bool: ... + def is_zero(self, __x: _Decimal) -> bool: ... + def ln(self, __x: _Decimal) -> Decimal: ... + def log10(self, __x: _Decimal) -> Decimal: ... + def logb(self, __x: _Decimal) -> Decimal: ... + def logical_and(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def logical_invert(self, __x: _Decimal) -> Decimal: ... + def logical_or(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def logical_xor(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def max(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def max_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def min(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def min_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def minus(self, __x: _Decimal) -> Decimal: ... + def multiply(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def next_minus(self, __x: _Decimal) -> Decimal: ... + def next_plus(self, __x: _Decimal) -> Decimal: ... + def next_toward(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def normalize(self, __x: _Decimal) -> Decimal: ... + def number_class(self, __x: _Decimal) -> str: ... + def plus(self, __x: _Decimal) -> Decimal: ... + def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = ...) -> Decimal: ... + def quantize(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def radix(self) -> Decimal: ... + def remainder(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def remainder_near(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def rotate(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def same_quantum(self, __x: _Decimal, __y: _Decimal) -> bool: ... + def scaleb(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def shift(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def sqrt(self, __x: _Decimal) -> Decimal: ... + def subtract(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... + def to_eng_string(self, __x: _Decimal) -> str: ... + def to_sci_string(self, __x: _Decimal) -> str: ... + def to_integral_exact(self, __x: _Decimal) -> Decimal: ... + def to_integral_value(self, __x: _Decimal) -> Decimal: ... + def to_integral(self, __x: _Decimal) -> Decimal: ... + +DefaultContext: Context +BasicContext: Context +ExtendedContext: Context diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi index 97ba17ae497d..f257b758eeab 100644 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ b/mypy/typeshed/stdlib/_dummy_thread.pyi @@ -1,5 +1,6 @@ +from collections.abc import Callable from types import TracebackType -from typing import Any, Callable, NoReturn +from typing import Any, NoReturn TIMEOUT_MAX: int error = RuntimeError diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index 1cbb8f1ee8c8..2daceaedd4ad 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,11 +1,13 @@ import sys +from collections.abc import Callable, Iterable, Mapping from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, TypeVar +from typing import Any, TypeVar +from typing_extensions import TypeAlias # TODO recursive type -_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] +_TF: TypeAlias = Callable[[FrameType, str, Any], Callable[..., Any] | None] -_PF = Callable[[FrameType, str, Any], None] +_PF: TypeAlias = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/_json.pyi b/mypy/typeshed/stdlib/_json.pyi index 962fa9ec257a..130f7ab92e97 100644 --- a/mypy/typeshed/stdlib/_json.pyi +++ b/mypy/typeshed/stdlib/_json.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable +from collections.abc import Callable +from typing import Any from typing_extensions import final @final diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 375d8e4ddfbf..92e04d0f499d 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,21 +1,7 @@ import sys -from typing import ( - Any, - AnyStr, - Callable, - Container, - Generic, - Iterable, - Mapping, - MutableMapping, - MutableSequence, - Protocol, - Sequence, - SupportsAbs, - TypeVar, - overload, -) -from typing_extensions import ParamSpec, SupportsIndex, final +from collections.abc import Callable, Container, Iterable, Mapping, MutableMapping, MutableSequence, Sequence +from typing import Any, AnyStr, Generic, Protocol, SupportsAbs, TypeVar, overload +from typing_extensions import ParamSpec, SupportsIndex, TypeAlias, final _R = TypeVar("_R") _T = TypeVar("_T") @@ -40,7 +26,7 @@ class _SupportsDunderLE(Protocol): class _SupportsDunderGE(Protocol): def __ge__(self, __other: Any) -> Any: ... -_SupportsComparison = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT +_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT class _SupportsInversion(Protocol[_T_co]): def __invert__(self) -> _T_co: ... diff --git a/mypy/typeshed/stdlib/_osx_support.pyi b/mypy/typeshed/stdlib/_osx_support.pyi index cb43fa93bb80..7fd0ee922ca6 100644 --- a/mypy/typeshed/stdlib/_osx_support.pyi +++ b/mypy/typeshed/stdlib/_osx_support.pyi @@ -1,5 +1,6 @@ import sys -from typing import Iterable, Sequence, TypeVar +from collections.abc import Iterable, Sequence +from typing import TypeVar _T = TypeVar("_T") _K = TypeVar("_K") diff --git a/mypy/typeshed/stdlib/_posixsubprocess.pyi b/mypy/typeshed/stdlib/_posixsubprocess.pyi index 5481100cacfc..2d221c4896f6 100644 --- a/mypy/typeshed/stdlib/_posixsubprocess.pyi +++ b/mypy/typeshed/stdlib/_posixsubprocess.pyi @@ -1,5 +1,5 @@ import sys -from typing import Callable, Sequence +from collections.abc import Callable, Sequence if sys.platform != "win32": def cloexec_pipe() -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/_pydecimal.pyi b/mypy/typeshed/stdlib/_pydecimal.pyi index c15a4a41747e..90dbef1dc2e2 100644 --- a/mypy/typeshed/stdlib/_pydecimal.pyi +++ b/mypy/typeshed/stdlib/_pydecimal.pyi @@ -2,7 +2,7 @@ import sys # This is a slight lie, the implementations aren't exactly identical # However, in all likelihood, the differences are inconsequential -from decimal import * +from _decimal import * if sys.version_info >= (3, 7): __all__ = [ diff --git a/mypy/typeshed/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi index 9aff4b3cb026..c4b235f0cd5b 100644 --- a/mypy/typeshed/stdlib/_random.pyi +++ b/mypy/typeshed/stdlib/_random.pyi @@ -1,5 +1,7 @@ +from typing_extensions import TypeAlias + # Actually Tuple[(int,) * 625] -_State = tuple[int, ...] +_State: TypeAlias = tuple[int, ...] class Random: def __init__(self, seed: object = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/_sitebuiltins.pyi b/mypy/typeshed/stdlib/_sitebuiltins.pyi index a71364b8db65..4a35921e1ef7 100644 --- a/mypy/typeshed/stdlib/_sitebuiltins.pyi +++ b/mypy/typeshed/stdlib/_sitebuiltins.pyi @@ -1,4 +1,5 @@ -from typing import ClassVar, Iterable, NoReturn +from collections.abc import Iterable +from typing import ClassVar, NoReturn from typing_extensions import Literal class Quitter: diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index a8cf16823d4e..2366412050cd 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -2,21 +2,22 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable from typing import Any, SupportsInt, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 8): from typing import SupportsIndex - _FD = SupportsIndex + _FD: TypeAlias = SupportsIndex else: - _FD = SupportsInt + _FD: TypeAlias = SupportsInt -_CMSG = tuple[int, int, bytes] -_CMSGArg = tuple[int, int, ReadableBuffer] +_CMSG: TypeAlias = tuple[int, int, bytes] +_CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = tuple[Any, ...] | str -_RetAddress = Any +_Address: TypeAlias = tuple[Any, ...] | str +_RetAddress: TypeAlias = Any # TODO Most methods allow bytes as address objects # ----- Constants ----- diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 04abf8dc869c..c5da8ccf3a90 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import structseq +from collections.abc import Callable from threading import Thread from types import TracebackType -from typing import Any, Callable, NoReturn +from typing import Any, NoReturn from typing_extensions import Final, final error = RuntimeError diff --git a/mypy/typeshed/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi index 2ad77a177c37..def996fba117 100644 --- a/mypy/typeshed/stdlib/_threading_local.pyi +++ b/mypy/typeshed/stdlib/_threading_local.pyi @@ -1,15 +1,16 @@ from typing import Any +from typing_extensions import TypeAlias from weakref import ReferenceType __all__ = ["local"] -localdict = dict[Any, Any] +_localdict: TypeAlias = dict[Any, Any] class _localimpl: key: str - dicts: dict[int, tuple[ReferenceType[Any], localdict]] + dicts: dict[int, tuple[ReferenceType[Any], _localdict]] def __init__(self) -> None: ... - def get_dict(self) -> localdict: ... - def create_dict(self) -> localdict: ... + def get_dict(self) -> _localdict: ... + def create_dict(self) -> _localdict: ... class local: def __getattribute__(self, name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/_tracemalloc.pyi b/mypy/typeshed/stdlib/_tracemalloc.pyi index fd159dc586cb..6e3c4e59a07a 100644 --- a/mypy/typeshed/stdlib/_tracemalloc.pyi +++ b/mypy/typeshed/stdlib/_tracemalloc.pyi @@ -1,6 +1,6 @@ import sys +from collections.abc import Sequence from tracemalloc import _FrameTupleT, _TraceTupleT -from typing import Sequence def _get_object_traceback(__obj: object) -> Sequence[_FrameTupleT] | None: ... def _get_traces() -> Sequence[_TraceTupleT]: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index b348a329522b..a80ea0702f77 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -6,8 +6,10 @@ import array import ctypes import mmap import sys +from collections.abc import Awaitable, Container, Iterable, Set as AbstractSet from os import PathLike -from typing import AbstractSet, Any, Awaitable, Container, Generic, Iterable, Protocol, TypeVar +from types import TracebackType +from typing import Any, Generic, Protocol, TypeVar, Union from typing_extensions import Final, Literal, TypeAlias, final _KT = TypeVar("_KT") @@ -99,7 +101,7 @@ StrPath: TypeAlias = str | PathLike[str] # stable BytesPath: TypeAlias = bytes | PathLike[bytes] # stable StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] # stable -OpenTextModeUpdating = Literal[ +OpenTextModeUpdating: TypeAlias = Literal[ "r+", "+r", "rt+", @@ -197,6 +199,9 @@ WriteableBuffer: TypeAlias = bytearray | memoryview | array.array[Any] | mmap.mm # Same as _WriteableBuffer, but also includes read-only buffer types (like bytes). ReadableBuffer: TypeAlias = ReadOnlyBuffer | WriteableBuffer # stable +ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType] +OptExcInfo: TypeAlias = Union[ExcInfo, tuple[None, None, None]] + # stable if sys.version_info >= (3, 10): from types import NoneType as NoneType diff --git a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index 9f036d8f2d33..81ca12910bd9 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -1,36 +1,44 @@ # Types to support PEP 3333 (WSGI) # +# Obsolete since Python 3.11: Use wsgiref.types instead. +# # See the README.md file in this directory for more information. -from sys import _OptExcInfo -from typing import Any, Callable, Iterable, Protocol +import sys +from _typeshed import OptExcInfo +from collections.abc import Callable, Iterable +from typing import Any, Protocol from typing_extensions import TypeAlias -# stable -class StartResponse(Protocol): - def __call__( - self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ... - ) -> Callable[[bytes], Any]: ... +class _Readable(Protocol): + def read(self, size: int = ...) -> bytes: ... + # Optional: def close(self) -> object: ... -WSGIEnvironment: TypeAlias = dict[str, Any] # stable -WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable +if sys.version_info >= (3, 11): + from wsgiref.types import * +else: + # stable + class StartResponse(Protocol): + def __call__( + self, __status: str, __headers: list[tuple[str, str]], __exc_info: OptExcInfo | None = ... + ) -> Callable[[bytes], object]: ... -# WSGI input streams per PEP 3333, stable -class InputStream(Protocol): - def read(self, size: int = ...) -> bytes: ... - def readline(self, size: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> list[bytes]: ... - def __iter__(self) -> Iterable[bytes]: ... + WSGIEnvironment: TypeAlias = dict[str, Any] # stable + WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable -# WSGI error streams per PEP 3333, stable -class ErrorStream(Protocol): - def flush(self) -> None: ... - def write(self, s: str) -> None: ... - def writelines(self, seq: list[str]) -> None: ... + # WSGI input streams per PEP 3333, stable + class InputStream(Protocol): + def read(self, __size: int = ...) -> bytes: ... + def readline(self, __size: int = ...) -> bytes: ... + def readlines(self, __hint: int = ...) -> list[bytes]: ... + def __iter__(self) -> Iterable[bytes]: ... -class _Readable(Protocol): - def read(self, size: int = ...) -> bytes: ... + # WSGI error streams per PEP 3333, stable + class ErrorStream(Protocol): + def flush(self) -> object: ... + def write(self, __s: str) -> object: ... + def writelines(self, __seq: list[str]) -> object: ... -# Optional file wrapper in wsgi.file_wrapper -class FileWrapper(Protocol): - def __call__(self, file: _Readable, block_size: int = ...) -> Iterable[bytes]: ... + # Optional file wrapper in wsgi.file_wrapper + class FileWrapper(Protocol): + def __call__(self, __file: _Readable, __block_size: int = ...) -> Iterable[bytes]: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index 00dc2d5114b8..2d3faec1fa68 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Callable, Generic, TypeVar, overload +from collections.abc import Callable +from typing import Any, Generic, TypeVar, overload from typing_extensions import final if sys.version_info >= (3, 9): @@ -28,10 +29,10 @@ class ReferenceType(Generic[_T]): ref = ReferenceType def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(object: Any) -> list[Any]: ... -@overload -def proxy(object: _C, callback: Callable[[_C], Any] | None = ...) -> CallableProxyType[_C]: ... +def getweakrefs(__object: Any) -> list[Any]: ... # Return CallableProxyType if object is callable, ProxyType otherwise @overload -def proxy(object: _T, callback: Callable[[_T], Any] | None = ...) -> Any: ... +def proxy(__object: _C, __callback: Callable[[_C], Any] | None = ...) -> CallableProxyType[_C]: ... +@overload +def proxy(__object: _T, __callback: Callable[[_T], Any] | None = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index b0c22a5ecc13..382dbdeb6c8a 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import Self -from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar +from collections.abc import Iterable, Iterator, MutableSet +from typing import Any, Generic, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index 1e8c51477083..77e7714454e7 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, NoReturn, Sequence, overload +from collections.abc import Sequence +from typing import Any, NoReturn, overload from typing_extensions import Literal, final if sys.platform == "win32": diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index db3d8d991029..14e824f3d22e 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self from types import TracebackType from typing import IO, Any, NamedTuple, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): __all__ = ["Error", "open"] @@ -19,8 +19,8 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = str | IO[bytes] -_Marker = tuple[int, int, bytes] +_File: TypeAlias = str | IO[bytes] +_Marker: TypeAlias = tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> None: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 0a56aa4f4b59..759027d3a890 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -1,20 +1,7 @@ import sys -from typing import ( - IO, - Any, - Callable, - Generator, - Generic, - Iterable, - NewType, - NoReturn, - Pattern, - Protocol, - Sequence, - TypeVar, - overload, -) -from typing_extensions import Literal +from collections.abc import Callable, Generator, Iterable, Sequence +from typing import IO, Any, Generic, NewType, NoReturn, Pattern, Protocol, TypeVar, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): __all__ = [ @@ -66,11 +53,11 @@ _N = TypeVar("_N") # "store_false", "append", "append_const", "count", "help", "version", # "extend"], but using this would make it hard to annotate callers # that don't use a literal argument -_ActionStr = str +_ActionStr: TypeAlias = str # more precisely, Literal["?", "*", "+", "...", "A...", # "==SUPPRESS=="], but using this would make it hard to annotate # callers that don't use a literal argument -_NArgsStr = str +_NArgsStr: TypeAlias = str ONE_OR_MORE: Literal["+"] OPTIONAL: Literal["?"] diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 69b4d35d9fe9..d69f02d338cf 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,12 +1,15 @@ import sys from _typeshed import Self -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, overload -from typing_extensions import Literal, SupportsIndex +from collections.abc import Iterable -_IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] -_FloatTypeCode = Literal["f", "d"] -_UnicodeTypeCode = Literal["u"] -_TypeCode = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode +# pytype crashes if array inherits from collections.abc.MutableSequence instead of typing.MutableSequence +from typing import Any, BinaryIO, Generic, MutableSequence, TypeVar, overload # noqa: Y027 +from typing_extensions import Literal, SupportsIndex, TypeAlias + +_IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] +_FloatTypeCode: TypeAlias = Literal["f", "d"] +_UnicodeTypeCode: TypeAlias = Literal["u"] +_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode _T = TypeVar("_T", int, float, str) diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 5a86d6888b2f..199e4f2acb68 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -1,15 +1,7 @@ -# Rename typing to _typing, as not to conflict with typing imported -# from _ast below when loaded in an unorthodox way by the Dropbox -# internal Bazel integration. - -# The same unorthodox Bazel integration causes issues with sys, which -# is imported in both modules. unfortunately we can't just rename sys, -# since mypy only supports version checks with a sys that is named -# sys. import sys -import typing as _typing from _ast import * -from typing import Any, Iterator, TypeVar, overload +from collections.abc import Iterator +from typing import Any, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 8): @@ -166,7 +158,7 @@ if sys.version_info >= (3, 8): mode: Literal["exec"] = ..., *, type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> Module: ... @overload def parse( @@ -175,7 +167,7 @@ if sys.version_info >= (3, 8): mode: Literal["eval"], *, type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> Expression: ... @overload def parse( @@ -184,7 +176,7 @@ if sys.version_info >= (3, 8): mode: Literal["func_type"], *, type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> FunctionType: ... @overload def parse( @@ -193,7 +185,7 @@ if sys.version_info >= (3, 8): mode: Literal["single"], *, type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> Interactive: ... @overload def parse( @@ -201,7 +193,7 @@ if sys.version_info >= (3, 8): *, mode: Literal["eval"], type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> Expression: ... @overload def parse( @@ -209,7 +201,7 @@ if sys.version_info >= (3, 8): *, mode: Literal["func_type"], type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> FunctionType: ... @overload def parse( @@ -217,7 +209,7 @@ if sys.version_info >= (3, 8): *, mode: Literal["single"], type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> Interactive: ... @overload def parse( @@ -226,7 +218,7 @@ if sys.version_info >= (3, 8): mode: str = ..., *, type_comments: bool = ..., - feature_version: None | int | _typing.Tuple[int, int] = ..., + feature_version: None | int | tuple[int, int] = ..., ) -> AST: ... else: @@ -260,7 +252,7 @@ def fix_missing_locations(node: _T) -> _T: ... def get_docstring(node: AST, clean: bool = ...) -> str | None: ... def increment_lineno(node: _T, n: int = ...) -> _T: ... def iter_child_nodes(node: AST) -> Iterator[AST]: ... -def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... +def iter_fields(node: AST) -> Iterator[tuple[str, Any]]: ... def literal_eval(node_or_string: str | AST) -> Any: ... if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 71e4487baf99..7742651fea2a 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -6,10 +6,10 @@ from asyncio.futures import Future from asyncio.protocols import BaseProtocol from asyncio.tasks import Task from asyncio.transports import BaseTransport, ReadTransport, SubprocessTransport, WriteTransport -from collections.abc import Iterable +from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable, Sequence from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, overload -from typing_extensions import Literal +from typing import IO, Any, TypeVar, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 7): from contextvars import Context @@ -23,10 +23,10 @@ else: _T = TypeVar("_T") _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) -_Context = dict[str, Any] -_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] -_ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = bool | None | ssl.SSLContext +_Context: TypeAlias = dict[str, Any] +_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], Any] +_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] +_SSLContext: TypeAlias = bool | None | ssl.SSLContext class Server(AbstractServer): if sys.version_info >= (3, 7): diff --git a/mypy/typeshed/stdlib/asyncio/base_futures.pyi b/mypy/typeshed/stdlib/asyncio/base_futures.pyi index 1b7fe4671ca8..8a973d1618f4 100644 --- a/mypy/typeshed/stdlib/asyncio/base_futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_futures.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Callable, Sequence +from collections.abc import Callable, Sequence +from typing import Any from typing_extensions import Literal if sys.version_info >= (3, 7): diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index 21c56bde1eac..963cfa93de28 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -1,10 +1,12 @@ import subprocess from collections import deque -from typing import IO, Any, Callable, Sequence +from collections.abc import Callable, Sequence +from typing import IO, Any +from typing_extensions import TypeAlias from . import events, futures, protocols, transports -_File = int | IO[Any] | None +_File: TypeAlias = int | IO[Any] | None class BaseSubprocessTransport(transports.SubprocessTransport): diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index cc0391f92bc4..ae566234160b 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -2,9 +2,10 @@ import ssl import sys from _typeshed import FileDescriptorLike, Self from abc import ABCMeta, abstractmethod +from collections.abc import Awaitable, Callable, Coroutine, Generator, Sequence from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, overload -from typing_extensions import Literal +from typing import IO, Any, TypeVar, overload +from typing_extensions import Literal, TypeAlias from .base_events import Server from .futures import Future @@ -75,10 +76,10 @@ else: _T = TypeVar("_T") _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) -_Context = dict[str, Any] -_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] -_ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = bool | None | ssl.SSLContext +_Context: TypeAlias = dict[str, Any] +_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], Any] +_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] +_SSLContext: TypeAlias = bool | None | ssl.SSLContext class Handle: _cancelled: bool diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index 5e483a578c3e..4e2ef8d3f274 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -1,12 +1,14 @@ import functools import traceback +from collections.abc import Iterable from types import FrameType, FunctionType -from typing import Any, Iterable, overload +from typing import Any, overload +from typing_extensions import TypeAlias class _HasWrapper: __wrapper__: _HasWrapper | FunctionType -_FuncType = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any] +_FuncType: TypeAlias = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any] @overload def _get_function_source(func: _FuncType) -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index 2b0b93a09638..692d263f673b 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Self +from collections.abc import Awaitable, Callable, Generator, Iterable from concurrent.futures._base import Error, Future as _ConcurrentFuture -from typing import Any, Awaitable, Callable, Generator, Iterable, TypeVar +from typing import Any, TypeVar from typing_extensions import Literal, TypeGuard from .events import AbstractEventLoop diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 01b1c5b4591d..2758e0c46919 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -1,7 +1,8 @@ import sys from collections import deque +from collections.abc import Callable, Generator from types import TracebackType -from typing import Any, Callable, Generator, TypeVar +from typing import Any, TypeVar from typing_extensions import Literal from .events import AbstractEventLoop diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index 4ffb40160420..21247401c9ba 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,6 +1,7 @@ import sys +from collections.abc import Mapping from socket import socket -from typing import Any, Mapping, Protocol +from typing import Any, Protocol from typing_extensions import Literal from . import base_events, constants, events, futures, streams, transports diff --git a/mypy/typeshed/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi index 7e799dd22fd8..32cd839f2f79 100644 --- a/mypy/typeshed/stdlib/asyncio/runners.pyi +++ b/mypy/typeshed/stdlib/asyncio/runners.pyi @@ -1,5 +1,6 @@ import sys -from typing import Awaitable, TypeVar +from collections.abc import Awaitable +from typing import TypeVar __all__ = ("run",) _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 4ecd7a11dd56..619e329bfb43 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -1,7 +1,8 @@ import ssl import sys from collections import deque -from typing import Any, Callable, ClassVar +from collections.abc import Callable +from typing import Any, ClassVar from typing_extensions import Literal from . import constants, events, futures, protocols, transports diff --git a/mypy/typeshed/stdlib/asyncio/staggered.pyi b/mypy/typeshed/stdlib/asyncio/staggered.pyi index fc4bfad76984..610d6f70b614 100644 --- a/mypy/typeshed/stdlib/asyncio/staggered.pyi +++ b/mypy/typeshed/stdlib/asyncio/staggered.pyi @@ -1,4 +1,5 @@ -from typing import Any, Awaitable, Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable +from typing import Any from . import events diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 666862cc7b7d..14a6d2c4d8fe 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -1,6 +1,8 @@ import sys from _typeshed import Self, StrPath -from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Sequence +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence +from typing import Any +from typing_extensions import TypeAlias from . import events, protocols, transports from .base_events import Server @@ -64,7 +66,7 @@ else: "start_unix_server", ] -_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] +_ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] if sys.version_info < (3, 8): class IncompleteReadError(EOFError): @@ -118,9 +120,9 @@ else: if sys.platform != "win32": if sys.version_info >= (3, 7): - _PathType = StrPath + _PathType: TypeAlias = StrPath else: - _PathType = str + _PathType: TypeAlias = str if sys.version_info >= (3, 10): async def open_unix_connection( path: _PathType | None = ..., *, limit: int = ..., **kwds: Any diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index 3a617d6fb628..55093a3ebd9f 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -2,8 +2,9 @@ import subprocess import sys from _typeshed import StrOrBytesPath from asyncio import events, protocols, streams, transports -from typing import IO, Any, Callable -from typing_extensions import Literal +from collections.abc import Callable +from typing import IO, Any +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 7): __all__ = ("create_subprocess_exec", "create_subprocess_shell") @@ -11,9 +12,9 @@ else: __all__ = ["create_subprocess_exec", "create_subprocess_shell"] if sys.version_info >= (3, 8): - _ExecArg = StrOrBytesPath + _ExecArg: TypeAlias = StrOrBytesPath else: - _ExecArg = str | bytes + _ExecArg: TypeAlias = str | bytes PIPE: int STDOUT: int diff --git a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi index ef04614c3c15..58e3d41e53f1 100644 --- a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi +++ b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi @@ -1,8 +1,9 @@ # This only exists in 3.11+. See VERSIONS. from _typeshed import Self +from collections.abc import Coroutine, Generator from types import TracebackType -from typing import Any, Coroutine, Generator, TypeVar +from typing import Any, TypeVar from .tasks import Task diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 885688065ddc..4a8e565afb2f 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -1,9 +1,9 @@ import concurrent.futures import sys -from collections.abc import Awaitable, Generator, Iterable, Iterator +from collections.abc import Awaitable, Coroutine, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Coroutine, Generic, TextIO, TypeVar, overload -from typing_extensions import Literal +from typing import Any, Generic, TextIO, TypeVar, overload +from typing_extensions import Literal, TypeAlias from .events import AbstractEventLoop from .futures import Future @@ -56,8 +56,8 @@ _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _FT = TypeVar("_FT", bound=Future[Any]) -_FutureT = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] -_TaskYieldType = Future[object] | None +_FutureT: TypeAlias = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] +_TaskYieldType: TypeAlias = Future[object] | None FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION diff --git a/mypy/typeshed/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi index ac3a5c56b222..88c4fddcaa3f 100644 --- a/mypy/typeshed/stdlib/asyncio/threads.pyi +++ b/mypy/typeshed/stdlib/asyncio/threads.pyi @@ -1,4 +1,5 @@ -from typing import Callable, TypeVar +from collections.abc import Callable +from typing import TypeVar from typing_extensions import ParamSpec __all__ = ("to_thread",) diff --git a/mypy/typeshed/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi index 90e54b547a87..a8cd753c2af8 100644 --- a/mypy/typeshed/stdlib/asyncio/transports.pyi +++ b/mypy/typeshed/stdlib/asyncio/transports.pyi @@ -1,8 +1,9 @@ import sys from asyncio.events import AbstractEventLoop from asyncio.protocols import BaseProtocol +from collections.abc import Mapping from socket import _Address -from typing import Any, Mapping +from typing import Any if sys.version_info >= (3, 7): __all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport") diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 3fe1e19d1311..20df2a78a5ab 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -1,14 +1,16 @@ import socket import sys from builtins import type as Type # alias to avoid name clashes with property named "type" +from collections.abc import Iterable from types import TracebackType -from typing import Any, BinaryIO, Iterable, NoReturn, overload +from typing import Any, BinaryIO, NoReturn, overload +from typing_extensions import TypeAlias # These are based in socket, maybe move them out into _typeshed.pyi or such -_Address = tuple[Any, ...] | str -_RetAddress = Any -_WriteBuffer = bytearray | memoryview -_CMSG = tuple[int, int, bytes] +_Address: TypeAlias = tuple[Any, ...] | str +_RetAddress: TypeAlias = Any +_WriteBuffer: TypeAlias = bytearray | memoryview +_CMSG: TypeAlias = tuple[int, int, bytes] class TransportSocket: def __init__(self, sock: socket.socket) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 78d87dc4e9e9..ca28ee04125a 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -2,8 +2,9 @@ import sys import types from _typeshed import Self from abc import ABCMeta, abstractmethod +from collections.abc import Callable from socket import socket -from typing import Any, Callable +from typing import Any from typing_extensions import Literal from .base_events import Server diff --git a/mypy/typeshed/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi index 1e4d286386c8..d33210bc1297 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_events.pyi @@ -1,7 +1,8 @@ import socket import sys from _typeshed import WriteableBuffer -from typing import IO, Any, Callable, ClassVar, NoReturn +from collections.abc import Callable +from typing import IO, Any, ClassVar, NoReturn from typing_extensions import Literal from . import events, futures, proactor_events, selector_events, streams, windows_utils diff --git a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index 1156f905659e..0a79635b3d4e 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -1,8 +1,9 @@ import subprocess import sys from _typeshed import Self +from collections.abc import Callable from types import TracebackType -from typing import Any, AnyStr, Callable, Protocol +from typing import Any, AnyStr, Protocol from typing_extensions import Literal if sys.platform == "win32": diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index 8f77e0e45c44..a4a774282343 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -2,10 +2,11 @@ import sys from _typeshed import FileDescriptorLike from socket import socket from typing import Any, overload +from typing_extensions import TypeAlias # cyclic dependence with asynchat -_maptype = dict[int, Any] -_socket = socket +_maptype: TypeAlias = dict[int, Any] +_socket: TypeAlias = socket socket_map: _maptype # undocumented diff --git a/mypy/typeshed/stdlib/atexit.pyi b/mypy/typeshed/stdlib/atexit.pyi index ba0c7dfaf6b1..095ab5f9b26d 100644 --- a/mypy/typeshed/stdlib/atexit.pyi +++ b/mypy/typeshed/stdlib/atexit.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable, TypeVar +from collections.abc import Callable +from typing import Any, TypeVar from typing_extensions import ParamSpec _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi index b08731b85b0b..62b54ced9127 100644 --- a/mypy/typeshed/stdlib/audioop.pyi +++ b/mypy/typeshed/stdlib/audioop.pyi @@ -1,10 +1,12 @@ -AdpcmState = tuple[int, int] -RatecvState = tuple[int, tuple[tuple[int, int], ...]] +from typing_extensions import TypeAlias + +_AdpcmState: TypeAlias = tuple[int, int] +_RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... def add(__fragment1: bytes, __fragment2: bytes, __width: int) -> bytes: ... -def adpcm2lin(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... +def adpcm2lin(__fragment: bytes, __width: int, __state: _AdpcmState | None) -> tuple[bytes, _AdpcmState]: ... def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... def avg(__fragment: bytes, __width: int) -> int: ... def avgpp(__fragment: bytes, __width: int) -> int: ... @@ -15,7 +17,7 @@ def findfactor(__fragment: bytes, __reference: bytes) -> float: ... def findfit(__fragment: bytes, __reference: bytes) -> tuple[int, float]: ... def findmax(__fragment: bytes, __length: int) -> int: ... def getsample(__fragment: bytes, __width: int, __index: int) -> int: ... -def lin2adpcm(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... +def lin2adpcm(__fragment: bytes, __width: int, __state: _AdpcmState | None) -> tuple[bytes, _AdpcmState]: ... def lin2alaw(__fragment: bytes, __width: int) -> bytes: ... def lin2lin(__fragment: bytes, __width: int, __newwidth: int) -> bytes: ... def lin2ulaw(__fragment: bytes, __width: int) -> bytes: ... @@ -29,10 +31,10 @@ def ratecv( __nchannels: int, __inrate: int, __outrate: int, - __state: RatecvState | None, + __state: _RatecvState | None, __weightA: int = ..., __weightB: int = ..., -) -> tuple[bytes, RatecvState]: ... +) -> tuple[bytes, _RatecvState]: ... def reverse(__fragment: bytes, __width: int) -> bytes: ... def rms(__fragment: bytes, __width: int) -> int: ... def tomono(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 8f61433e0cb8..bbd0f20af6c8 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,20 +1,20 @@ +from _typeshed import ExcInfo +from collections.abc import Callable, Iterable, Mapping from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, TypeVar -from typing_extensions import Literal, ParamSpec +from typing import IO, Any, SupportsInt, TypeVar +from typing_extensions import Literal, ParamSpec, TypeAlias __all__ = ["BdbQuit", "Bdb", "Breakpoint"] _T = TypeVar("_T") _P = ParamSpec("_P") -_TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = tuple[type[BaseException], BaseException, FrameType] +_TraceDispatch: TypeAlias = Callable[[FrameType, str, Any], Any] # TODO: Recursive type GENERATOR_AND_COROUTINE_FLAGS: Literal[672] class BdbQuit(Exception): ... class Bdb: - skip: set[str] | None breaks: dict[str, list[int]] fncache: dict[str, str] @@ -31,7 +31,7 @@ class Bdb: def dispatch_line(self, frame: FrameType) -> _TraceDispatch: ... def dispatch_call(self, frame: FrameType, arg: None) -> _TraceDispatch: ... def dispatch_return(self, frame: FrameType, arg: Any) -> _TraceDispatch: ... - def dispatch_exception(self, frame: FrameType, arg: _ExcInfo) -> _TraceDispatch: ... + def dispatch_exception(self, frame: FrameType, arg: ExcInfo) -> _TraceDispatch: ... def is_skipped_module(self, module_name: str) -> bool: ... def stop_here(self, frame: FrameType) -> bool: ... def break_here(self, frame: FrameType) -> bool: ... @@ -40,7 +40,7 @@ class Bdb: def user_call(self, frame: FrameType, argument_list: None) -> None: ... def user_line(self, frame: FrameType) -> None: ... def user_return(self, frame: FrameType, return_value: Any) -> None: ... - def user_exception(self, frame: FrameType, exc_info: _ExcInfo) -> None: ... + def user_exception(self, frame: FrameType, exc_info: ExcInfo) -> None: ... def set_until(self, frame: FrameType, lineno: int | None = ...) -> None: ... def set_step(self) -> None: ... def set_next(self, frame: FrameType) -> None: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 317bb9979b92..53f72ad6a88f 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -1,36 +1,44 @@ import sys +from _typeshed import ReadableBuffer +from typing_extensions import TypeAlias -def a2b_uu(__data: str | bytes) -> bytes: ... +# Many functions in binascii accept buffer objects +# or ASCII-only strings. +_AsciiBuffer: TypeAlias = str | ReadableBuffer + +def a2b_uu(__data: _AsciiBuffer) -> bytes: ... if sys.version_info >= (3, 7): - def b2a_uu(__data: bytes, *, backtick: bool = ...) -> bytes: ... + def b2a_uu(__data: ReadableBuffer, *, backtick: bool = ...) -> bytes: ... else: - def b2a_uu(__data: bytes) -> bytes: ... + def b2a_uu(__data: ReadableBuffer) -> bytes: ... -def a2b_base64(__data: str | bytes) -> bytes: ... -def b2a_base64(__data: bytes, *, newline: bool = ...) -> bytes: ... -def a2b_qp(data: str | bytes, header: bool = ...) -> bytes: ... -def b2a_qp(data: bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... +def a2b_base64(__data: _AsciiBuffer) -> bytes: ... +def b2a_base64(__data: ReadableBuffer, *, newline: bool = ...) -> bytes: ... +def a2b_qp(data: _AsciiBuffer, header: bool = ...) -> bytes: ... +def b2a_qp(data: ReadableBuffer, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... if sys.version_info < (3, 11): - def a2b_hqx(__data: str | bytes) -> bytes: ... - def rledecode_hqx(__data: bytes) -> bytes: ... - def rlecode_hqx(__data: bytes) -> bytes: ... - def b2a_hqx(__data: bytes) -> bytes: ... + def a2b_hqx(__data: _AsciiBuffer) -> bytes: ... + def rledecode_hqx(__data: ReadableBuffer) -> bytes: ... + def rlecode_hqx(__data: ReadableBuffer) -> bytes: ... + def b2a_hqx(__data: ReadableBuffer) -> bytes: ... -def crc_hqx(__data: bytes, __crc: int) -> int: ... -def crc32(__data: bytes, __crc: int = ...) -> int: ... -def b2a_hex(__data: bytes) -> bytes: ... +def crc_hqx(__data: ReadableBuffer, __crc: int) -> int: ... +def crc32(__data: ReadableBuffer, __crc: int = ...) -> int: ... if sys.version_info >= (3, 8): - def hexlify(data: bytes, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... + # sep must be str or bytes, not bytearray or any other buffer + def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... + def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... else: - def hexlify(__data: bytes) -> bytes: ... + def b2a_hex(__data: ReadableBuffer) -> bytes: ... + def hexlify(__data: ReadableBuffer) -> bytes: ... -def a2b_hex(__hexstr: str | bytes) -> bytes: ... -def unhexlify(__hexstr: str | bytes) -> bytes: ... +def a2b_hex(__hexstr: _AsciiBuffer) -> bytes: ... +def unhexlify(__hexstr: _AsciiBuffer) -> bytes: ... class Error(ValueError): ... class Incomplete(Exception): ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index db002503c75f..27aa379f134d 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,5 +1,5 @@ from typing import IO, Any -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["binhex", "hexbin", "Error"] @@ -15,8 +15,8 @@ class FInfo: Creator: str Flags: int -_FileInfoTuple = tuple[str, FInfo, int, int] -_FileHandleUnion = str | IO[bytes] +_FileInfoTuple: TypeAlias = tuple[str, FInfo, int, int] +_FileHandleUnion: TypeAlias = str | IO[bytes] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 9c5dfcfef22f..bf1e6cde2c08 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -22,29 +22,24 @@ from _typeshed import ( SupportsTrunc, SupportsWrite, ) -from collections.abc import Callable +from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Reversible, Set as AbstractSet, Sized from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from types import CodeType, TracebackType, _Cell -from typing import ( + +# mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} are imported from collections.abc in builtins.pyi +from typing import ( # noqa: Y027 IO, - AbstractSet, Any, - Awaitable, BinaryIO, ByteString, ClassVar, Generic, - Iterable, - Iterator, Mapping, MutableMapping, MutableSequence, - MutableSet, NoReturn, Protocol, - Reversible, Sequence, - Sized, SupportsAbs, SupportsBytes, SupportsComplex, @@ -54,7 +49,7 @@ from typing import ( TypeVar, overload, ) -from typing_extensions import Literal, SupportsIndex, TypeGuard, final +from typing_extensions import Literal, SupportsIndex, TypeAlias, TypeGuard, final if sys.version_info >= (3, 9): from types import GenericAlias @@ -194,12 +189,12 @@ class super: @overload def __init__(self) -> None: ... -_PositiveInteger = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] -_NegativeInteger = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] +_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] class int: @overload - def __new__(cls: type[Self], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> Self: ... + def __new__(cls: type[Self], __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> Self: ... @overload def __new__(cls: type[Self], __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ... if sys.version_info >= (3, 8): @@ -218,15 +213,29 @@ class int: if sys.version_info >= (3, 10): def bit_count(self) -> int: ... - def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = ...) -> bytes: ... - @classmethod - def from_bytes( - cls: type[Self], - bytes: Iterable[SupportsIndex] | SupportsBytes, # TODO buffer object argument - byteorder: Literal["little", "big"], - *, - signed: bool = ..., - ) -> Self: ... + if sys.version_info >= (3, 11): + def to_bytes( + self, length: SupportsIndex = ..., byteorder: Literal["little", "big"] = ..., *, signed: bool = ... + ) -> bytes: ... + @classmethod + def from_bytes( + cls: type[Self], + bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer, + byteorder: Literal["little", "big"] = ..., + *, + signed: bool = ..., + ) -> Self: ... + else: + def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes( + cls: type[Self], + bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer, + byteorder: Literal["little", "big"], + *, + signed: bool = ..., + ) -> Self: ... + def __add__(self, __x: int) -> int: ... def __sub__(self, __x: int) -> int: ... def __mul__(self, __x: int) -> int: ... @@ -288,7 +297,7 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: type[Self], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> Self: ... + def __new__(cls: type[Self], x: SupportsFloat | SupportsIndex | str | ReadableBuffer = ...) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @@ -382,7 +391,7 @@ class str(Sequence[str]): @overload def __new__(cls: type[Self], object: object = ...) -> Self: ... @overload - def __new__(cls: type[Self], object: bytes, encoding: str = ..., errors: str = ...) -> Self: ... + def __new__(cls: type[Self], object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... def capitalize(self) -> str: ... def casefold(self) -> str: ... def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... @@ -479,11 +488,14 @@ class bytes(ByteString): def capitalize(self) -> bytes: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def count( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... def endswith( - self, __suffix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + __suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + __start: SupportsIndex | None = ..., + __end: SupportsIndex | None = ..., ) -> bool: ... if sys.version_info >= (3, 8): def expandtabs(self, tabsize: SupportsIndex = ...) -> bytes: ... @@ -491,7 +503,7 @@ class bytes(ByteString): def expandtabs(self, tabsize: int = ...) -> bytes: ... def find( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... if sys.version_info >= (3, 8): def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... @@ -499,7 +511,7 @@ class bytes(ByteString): def hex(self) -> str: ... def index( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... @@ -511,41 +523,44 @@ class bytes(ByteString): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[ByteString | memoryview]) -> bytes: ... - def ljust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... + def join(self, __iterable_of_bytes: Iterable[ReadableBuffer]) -> bytes: ... + def ljust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = ...) -> bytes: ... def lower(self) -> bytes: ... - def lstrip(self, __bytes: bytes | None = ...) -> bytes: ... - def partition(self, __sep: bytes) -> tuple[bytes, bytes, bytes]: ... - def replace(self, __old: bytes, __new: bytes, __count: SupportsIndex = ...) -> bytes: ... + def lstrip(self, __bytes: ReadableBuffer | None = ...) -> bytes: ... + def partition(self, __sep: ReadableBuffer) -> tuple[bytes, bytes, bytes]: ... + def replace(self, __old: ReadableBuffer, __new: ReadableBuffer, __count: SupportsIndex = ...) -> bytes: ... if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytes: ... - def removesuffix(self, __suffix: bytes) -> bytes: ... + def removeprefix(self, __prefix: ReadableBuffer) -> bytes: ... + def removesuffix(self, __suffix: ReadableBuffer) -> bytes: ... def rfind( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def rindex( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... - def rpartition(self, __sep: bytes) -> tuple[bytes, bytes, bytes]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... - def rstrip(self, __bytes: bytes | None = ...) -> bytes: ... - def split(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... + def rjust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = ...) -> bytes: ... + def rpartition(self, __sep: ReadableBuffer) -> tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: ReadableBuffer | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... + def rstrip(self, __bytes: ReadableBuffer | None = ...) -> bytes: ... + def split(self, sep: ReadableBuffer | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... def splitlines(self, keepends: bool = ...) -> list[bytes]: ... def startswith( - self, __prefix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + __prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + __start: SupportsIndex | None = ..., + __end: SupportsIndex | None = ..., ) -> bool: ... - def strip(self, __bytes: bytes | None = ...) -> bytes: ... + def strip(self, __bytes: ReadableBuffer | None = ...) -> bytes: ... def swapcase(self) -> bytes: ... def title(self) -> bytes: ... - def translate(self, __table: bytes | None, delete: bytes = ...) -> bytes: ... + def translate(self, __table: ReadableBuffer | None, delete: bytes = ...) -> bytes: ... def upper(self) -> bytes: ... def zfill(self, __width: SupportsIndex) -> bytes: ... @classmethod def fromhex(cls: type[Self], __s: str) -> Self: ... @staticmethod - def maketrans(__frm: bytes, __to: bytes) -> bytes: ... + def maketrans(__frm: ReadableBuffer, __to: ReadableBuffer) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... def __hash__(self) -> int: ... @@ -553,7 +568,7 @@ class bytes(ByteString): def __getitem__(self, __i: SupportsIndex) -> int: ... @overload def __getitem__(self, __s: slice) -> bytes: ... - def __add__(self, __s: bytes) -> bytes: ... + def __add__(self, __s: ReadableBuffer) -> bytes: ... def __mul__(self, __n: SupportsIndex) -> bytes: ... def __rmul__(self, __n: SupportsIndex) -> bytes: ... def __mod__(self, __value: Any) -> bytes: ... @@ -582,12 +597,15 @@ class bytearray(MutableSequence[int], ByteString): def capitalize(self) -> bytearray: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... def count( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def copy(self) -> bytearray: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... def endswith( - self, __suffix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + __suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + __start: SupportsIndex | None = ..., + __end: SupportsIndex | None = ..., ) -> bool: ... if sys.version_info >= (3, 8): def expandtabs(self, tabsize: SupportsIndex = ...) -> bytearray: ... @@ -596,7 +614,7 @@ class bytearray(MutableSequence[int], ByteString): def extend(self, __iterable_of_ints: Iterable[SupportsIndex]) -> None: ... def find( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... if sys.version_info >= (3, 8): def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... @@ -604,7 +622,7 @@ class bytearray(MutableSequence[int], ByteString): def hex(self) -> str: ... def index( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def insert(self, __index: SupportsIndex, __item: SupportsIndex) -> None: ... def isalnum(self) -> bool: ... @@ -617,43 +635,46 @@ class bytearray(MutableSequence[int], ByteString): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable_of_bytes: Iterable[ByteString | memoryview]) -> bytearray: ... - def ljust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... + def join(self, __iterable_of_bytes: Iterable[ReadableBuffer]) -> bytearray: ... + def ljust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = ...) -> bytearray: ... def lower(self) -> bytearray: ... - def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... + def lstrip(self, __bytes: ReadableBuffer | None = ...) -> bytearray: ... + def partition(self, __sep: ReadableBuffer) -> tuple[bytearray, bytearray, bytearray]: ... def pop(self, __index: int = ...) -> int: ... def remove(self, __value: int) -> None: ... if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: bytes) -> bytearray: ... - def removesuffix(self, __suffix: bytes) -> bytearray: ... + def removeprefix(self, __prefix: ReadableBuffer) -> bytearray: ... + def removesuffix(self, __suffix: ReadableBuffer) -> bytearray: ... - def replace(self, __old: bytes, __new: bytes, __count: SupportsIndex = ...) -> bytearray: ... + def replace(self, __old: ReadableBuffer, __new: ReadableBuffer, __count: SupportsIndex = ...) -> bytearray: ... def rfind( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def rindex( - self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... - def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... + def rjust(self, __width: SupportsIndex, __fillchar: bytes | bytearray = ...) -> bytearray: ... + def rpartition(self, __sep: ReadableBuffer) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: ReadableBuffer | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... + def rstrip(self, __bytes: ReadableBuffer | None = ...) -> bytearray: ... + def split(self, sep: ReadableBuffer | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... def startswith( - self, __prefix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, + __prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + __start: SupportsIndex | None = ..., + __end: SupportsIndex | None = ..., ) -> bool: ... - def strip(self, __bytes: bytes | None = ...) -> bytearray: ... + def strip(self, __bytes: ReadableBuffer | None = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... - def translate(self, __table: bytes | None, delete: bytes = ...) -> bytearray: ... + def translate(self, __table: ReadableBuffer | None, delete: bytes = ...) -> bytearray: ... def upper(self) -> bytearray: ... def zfill(self, __width: SupportsIndex) -> bytearray: ... @classmethod def fromhex(cls: type[Self], __string: str) -> Self: ... @staticmethod - def maketrans(__frm: bytes, __to: bytes) -> bytes: ... + def maketrans(__frm: ReadableBuffer, __to: ReadableBuffer) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... __hash__: ClassVar[None] # type: ignore[assignment] @@ -666,14 +687,15 @@ class bytearray(MutableSequence[int], ByteString): @overload def __setitem__(self, __s: slice, __x: Iterable[SupportsIndex] | bytes) -> None: ... def __delitem__(self, __i: SupportsIndex | slice) -> None: ... - def __add__(self, __s: bytes) -> bytearray: ... - def __iadd__(self: Self, __s: Iterable[int]) -> Self: ... + def __add__(self, __s: ReadableBuffer) -> bytearray: ... + # The superclass wants us to accept Iterable[int], but that fails at runtime. + def __iadd__(self: Self, __s: ReadableBuffer) -> Self: ... # type: ignore[override] def __mul__(self, __n: SupportsIndex) -> bytearray: ... def __rmul__(self, __n: SupportsIndex) -> bytearray: ... def __imul__(self: Self, __n: SupportsIndex) -> Self: ... def __mod__(self, __value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, __o: SupportsIndex | bytes) -> bool: ... # type: ignore[override] + def __contains__(self, __o: SupportsIndex | ReadableBuffer) -> bool: ... # type: ignore[override] def __eq__(self, __x: object) -> bool: ... def __ne__(self, __x: object) -> bool: ... def __lt__(self, __x: bytes) -> bool: ... @@ -722,7 +744,7 @@ class memoryview(Sized, Sequence[int]): def __iter__(self) -> Iterator[int]: ... def __len__(self) -> int: ... @overload - def __setitem__(self, __s: slice, __o: bytes) -> None: ... + def __setitem__(self, __s: slice, __o: ReadableBuffer) -> None: ... @overload def __setitem__(self, __i: SupportsIndex, __o: SupportsIndex) -> None: ... if sys.version_info >= (3, 8): @@ -1086,8 +1108,8 @@ if sys.version_info >= (3, 10): # TODO: `compile` has a more precise return type in reality; work on a way of expressing that? if sys.version_info >= (3, 8): def compile( - source: str | bytes | AST, - filename: str | bytes | _PathLike[Any], + source: str | ReadableBuffer | AST, + filename: str | ReadableBuffer | _PathLike[Any], mode: str, flags: int = ..., dont_inherit: int = ..., @@ -1098,8 +1120,8 @@ if sys.version_info >= (3, 8): else: def compile( - source: str | bytes | AST, - filename: str | bytes | _PathLike[Any], + source: str | ReadableBuffer | AST, + filename: str | ReadableBuffer | _PathLike[Any], mode: str, flags: int = ..., dont_inherit: int = ..., @@ -1118,12 +1140,12 @@ def divmod(__x: _T_contra, __y: SupportsRDivMod[_T_contra, _T_co]) -> _T_co: ... # The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance. # (The `globals` argument has to be a "real dict", rather than any old mapping, unlike the `locals` argument.) def eval( - __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... + __source: str | ReadableBuffer | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... ) -> Any: ... # Comment above regarding `eval` applies to `exec` as well def exec( - __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... + __source: str | ReadableBuffer | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... ) -> None: ... def exit(code: object = ...) -> NoReturn: ... @@ -1262,8 +1284,8 @@ def next(__i: SupportsNext[_T]) -> _T: ... def next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ... def oct(__number: int | SupportsIndex) -> str: ... -_OpenFile = StrOrBytesPath | int -_Opener = Callable[[str, int], int] +_OpenFile = StrOrBytesPath | int # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed +_Opener: TypeAlias = Callable[[str, int], int] # Text mode: always returns a TextIOWrapper @overload @@ -1351,7 +1373,7 @@ def open( closefd: bool = ..., opener: _Opener | None = ..., ) -> IO[Any]: ... -def ord(__c: str | bytes) -> int: ... +def ord(__c: str | bytes | bytearray) -> int: ... class _SupportsWriteAndFlush(SupportsWrite[_T_contra], Protocol[_T_contra]): def flush(self) -> None: ... @@ -1381,7 +1403,9 @@ class _SupportsPow3NoneOnly(Protocol[_E, _T_co]): class _SupportsPow3(Protocol[_E, _M, _T_co]): def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... -_SupportsSomeKindOfPow = _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] +_SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] +) if sys.version_info >= (3, 8): @overload @@ -1712,7 +1736,7 @@ class UnicodeDecodeError(UnicodeError): start: int end: int reason: str - def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, __reason: str) -> None: ... + def __init__(self, __encoding: str, __object: ReadableBuffer, __start: int, __end: int, __reason: str) -> None: ... class UnicodeEncodeError(UnicodeError): encoding: str @@ -1770,6 +1794,7 @@ if sys.version_info >= (3, 11): @overload def split(self: Self, __condition: Callable[[_BaseExceptionT_co], bool]) -> tuple[Self | None, Self | None]: ... def derive(self: Self, __excs: Sequence[_BaseExceptionT_co]) -> Self: ... + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): def __new__(cls: type[Self], __message: str, __exceptions: Sequence[_ExceptionT_co]) -> Self: ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index f1467acadd10..cea317e28037 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -2,8 +2,9 @@ import _compression import sys from _compression import BaseStream from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import IO, Any, Iterable, Protocol, TextIO, overload -from typing_extensions import Literal, SupportsIndex, final +from collections.abc import Iterable +from typing import IO, Any, Protocol, TextIO, overload +from typing_extensions import Literal, SupportsIndex, TypeAlias, final __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"] @@ -21,10 +22,10 @@ class _WritableFileobj(Protocol): def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... -_ReadBinaryMode = Literal["", "r", "rb"] -_WriteBinaryMode = Literal["w", "wb", "x", "xb", "a", "ab"] -_ReadTextMode = Literal["rt"] -_WriteTextMode = Literal["wt", "xt", "at"] +_ReadBinaryMode: TypeAlias = Literal["", "r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_ReadTextMode: TypeAlias = Literal["rt"] +_WriteTextMode: TypeAlias = Literal["wt", "xt", "at"] @overload def open( diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index 6f15e461e007..6e21fc92ade5 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import Self, StrOrBytesPath +from collections.abc import Callable from types import CodeType -from typing import Any, Callable, TypeVar -from typing_extensions import ParamSpec +from typing import Any, TypeVar +from typing_extensions import ParamSpec, TypeAlias __all__ = ["run", "runctx", "Profile"] @@ -13,7 +14,7 @@ def runctx( _T = TypeVar("_T") _P = ParamSpec("_P") -_Label = tuple[str, int, str] +_Label: TypeAlias = tuple[str, int, str] class Profile: stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index f106eb1213f1..c7e0a6b4606f 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -2,7 +2,7 @@ import datetime import sys from collections.abc import Iterable, Sequence from time import struct_time -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 10): __all__ = [ @@ -66,7 +66,7 @@ else: "weekheader", ] -_LocaleType = tuple[str | None, str | None] +_LocaleType: TypeAlias = tuple[str | None, str | None] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 0bd4e515ce51..5e7bebc2a7f8 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import Self, SupportsGetItem, SupportsItemAccess -from builtins import type as _type +from builtins import list as _list, type as _type from collections.abc import Iterable, Iterator, Mapping from types import TracebackType from typing import IO, Any, Protocol @@ -87,8 +87,6 @@ class MiniFieldStorage: value: Any def __init__(self, name: Any, value: Any) -> None: ... -_list = list - class FieldStorage: FieldStorageClass: _type | None keep_blank_values: int diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index 2db108ce75ec..ea5a8341bc5e 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,8 +1,7 @@ -from _typeshed import StrOrBytesPath +from _typeshed import OptExcInfo, StrOrBytesPath +from collections.abc import Callable from types import FrameType, TracebackType -from typing import IO, Any, Callable - -_ExcInfo = tuple[type[BaseException] | None, BaseException | None, TracebackType | None] +from typing import IO, Any __UNDEF__: object # undocumented sentinel @@ -14,8 +13,8 @@ def lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | N def scanvars( reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any] ) -> list[tuple[str, str | None, Any]]: ... # undocumented -def html(einfo: _ExcInfo, context: int = ...) -> str: ... -def text(einfo: _ExcInfo, context: int = ...) -> str: ... +def html(einfo: OptExcInfo, context: int = ...) -> str: ... +def text(einfo: OptExcInfo, context: int = ...) -> str: ... class Hook: # undocumented def __init__( @@ -27,7 +26,7 @@ class Hook: # undocumented format: str = ..., ) -> None: ... def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... - def handle(self, info: _ExcInfo | None = ...) -> None: ... + def handle(self, info: OptExcInfo | None = ...) -> None: ... -def handler(info: _ExcInfo | None = ...) -> None: ... +def handler(info: OptExcInfo | None = ...) -> None: ... def enable(display: int = ..., logdir: StrOrBytesPath | None = ..., context: int = ..., format: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index ee51861fdaa0..30ada5d5b5ef 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,5 +1,6 @@ import sys from typing import SupportsComplex, SupportsFloat +from typing_extensions import TypeAlias if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -13,9 +14,9 @@ nanj: complex tau: float if sys.version_info >= (3, 8): - _C = SupportsFloat | SupportsComplex | SupportsIndex | complex + _C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex else: - _C = SupportsFloat | SupportsComplex | complex + _C: TypeAlias = SupportsFloat | SupportsComplex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/cmd.pyi b/mypy/typeshed/stdlib/cmd.pyi index d1166db0f507..ddefff2edf05 100644 --- a/mypy/typeshed/stdlib/cmd.pyi +++ b/mypy/typeshed/stdlib/cmd.pyi @@ -1,4 +1,5 @@ -from typing import IO, Any, Callable +from collections.abc import Callable +from typing import IO, Any from typing_extensions import Literal __all__ = ["Cmd"] diff --git a/mypy/typeshed/stdlib/code.pyi b/mypy/typeshed/stdlib/code.pyi index 185c15853b82..59318aa353e2 100644 --- a/mypy/typeshed/stdlib/code.pyi +++ b/mypy/typeshed/stdlib/code.pyi @@ -1,6 +1,7 @@ from codeop import CommandCompiler +from collections.abc import Callable, Mapping from types import CodeType -from typing import Any, Callable, Mapping +from typing import Any __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 8fa93961d9d0..bba7703c7d33 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -2,8 +2,9 @@ import sys import types from _typeshed import Self from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, overload -from typing_extensions import Literal +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import IO, Any, BinaryIO, Protocol, TextIO, overload +from typing_extensions import Literal, TypeAlias __all__ = [ "register", @@ -83,7 +84,7 @@ class _IncrementalDecoder(Protocol): # The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 # https://docs.python.org/3/library/codecs.html#binary-transforms -_BytesToBytesEncoding = Literal[ +_BytesToBytesEncoding: TypeAlias = Literal[ "base64", "base_64", "base64_codec", @@ -102,7 +103,7 @@ _BytesToBytesEncoding = Literal[ "zlib_codec", ] # https://docs.python.org/3/library/codecs.html#text-transforms -_StrToStrEncoding = Literal["rot13", "rot_13"] +_StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"] @overload def encode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index e534c13c026b..2e88c0d8f474 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -8,7 +8,7 @@ if sys.version_info >= (3, 9): from types import GenericAlias if sys.version_info >= (3, 10): - from typing import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Reversible, Sequence + from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Reversible, Sequence else: from _collections_abc import * diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index 4967d01f90dc..5b756d87d118 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -2,10 +2,10 @@ import sys import threading from _typeshed import Self from abc import abstractmethod -from collections.abc import Container, Iterable, Iterator, Sequence +from collections.abc import Callable, Container, Iterable, Iterator, Sequence from logging import Logger from types import TracebackType -from typing import Any, Callable, Generic, Protocol, TypeVar, overload +from typing import Any, Generic, Protocol, TypeVar, overload from typing_extensions import Literal, ParamSpec, SupportsIndex if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index 0c6c403949ad..4cfa8276897f 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -1,11 +1,11 @@ import sys -from collections.abc import Generator, Iterable, Mapping, MutableMapping, MutableSequence +from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping, MutableSequence from multiprocessing.connection import Connection from multiprocessing.context import BaseContext, Process from multiprocessing.queues import Queue, SimpleQueue from threading import Lock, Semaphore, Thread from types import TracebackType -from typing import Any, Callable, Generic, TypeVar +from typing import Any, Generic, TypeVar from weakref import ref from ._base import Executor, Future diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index 46ca681c54fc..e10254531788 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -1,8 +1,8 @@ import queue import sys -from collections.abc import Iterable, Mapping, Set as AbstractSet +from collections.abc import Callable, Iterable, Mapping, Set as AbstractSet from threading import Lock, Semaphore, Thread -from typing import Any, Callable, Generic, TypeVar +from typing import Any, Generic, TypeVar from weakref import ref from ._base import Executor, Future diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index 55df2ce58de7..5ffac353ab31 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import StrOrBytesPath, StrPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence from typing import Any, ClassVar, Pattern, TypeVar, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = [ "NoSectionError", @@ -29,16 +29,16 @@ __all__ = [ ] # Internal type aliases -_section = Mapping[str, str] -_parser = MutableMapping[str, _section] -_converter = Callable[[str], Any] -_converters = dict[str, _converter] +_section: TypeAlias = Mapping[str, str] +_parser: TypeAlias = MutableMapping[str, _section] +_converter: TypeAlias = Callable[[str], Any] +_converters: TypeAlias = dict[str, _converter] _T = TypeVar("_T") if sys.version_info >= (3, 7): - _Path = StrOrBytesPath + _Path: TypeAlias = StrOrBytesPath else: - _Path = StrPath + _Path: TypeAlias = StrPath DEFAULTSECT: Literal["DEFAULT"] MAX_INTERPOLATION_DEPTH: Literal[10] diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index a60f8811e0ac..c93eeac3b44f 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,22 +1,9 @@ import sys from _typeshed import Self, StrOrBytesPath +from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType -from typing import ( # noqa: Y027 - IO, - Any, - AsyncGenerator, - AsyncIterator, - Awaitable, - Callable, - ContextManager, - Generator, - Generic, - Iterator, - Protocol, - TypeVar, - overload, -) -from typing_extensions import ParamSpec +from typing import IO, Any, ContextManager, Generic, Protocol, TypeVar, overload # noqa: Y027 +from typing_extensions import ParamSpec, TypeAlias if sys.version_info >= (3, 11): __all__ = [ @@ -90,7 +77,7 @@ _T_io = TypeVar("_T_io", bound=IO[str] | None) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") -_ExitFunc = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] +_ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] _CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) class ContextDecorator: @@ -189,7 +176,7 @@ class ExitStack(AbstractContextManager[ExitStack]): ) -> bool: ... if sys.version_info >= (3, 7): - _ExitCoroFunc = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] + _ExitCoroFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index 6b5661dd69eb..341cd8491caf 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar, overload +from collections.abc import Callable, Iterator, Mapping +from typing import Any, ClassVar, Generic, TypeVar, overload from typing_extensions import ParamSpec, final if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi index 4844a8028c5c..4403550b587e 100644 --- a/mypy/typeshed/stdlib/copyreg.pyi +++ b/mypy/typeshed/stdlib/copyreg.pyi @@ -1,7 +1,9 @@ -from typing import Any, Callable, Hashable, SupportsInt, TypeVar, Union +from collections.abc import Callable, Hashable +from typing import Any, SupportsInt, TypeVar, Union +from typing_extensions import TypeAlias _T = TypeVar("_T") -_Reduce = Union[tuple[Callable[..., _T], tuple[Any, ...]], tuple[Callable[..., _T], tuple[Any, ...], Any | None]] +_Reduce: TypeAlias = Union[tuple[Callable[..., _T], tuple[Any, ...]], tuple[Callable[..., _T], tuple[Any, ...], Any | None]] __all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] @@ -15,5 +17,5 @@ def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: def remove_extension(module: Hashable, name: Hashable, code: int) -> None: ... def clear_extension_cache() -> None: ... -_DispatchTableType = dict[type, Callable[[Any], str | _Reduce[Any]]] # imported by multiprocessing.reduction +_DispatchTableType: TypeAlias = dict[type, Callable[[Any], str | _Reduce[Any]]] # imported by multiprocessing.reduction dispatch_table: _DispatchTableType # undocumented diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 4a03886e8dd2..53a382ec0e71 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -1,7 +1,9 @@ import sys from _typeshed import ReadableBuffer, Self, WriteableBuffer from abc import abstractmethod -from typing import Any, Callable, ClassVar, Generic, Iterable, Iterator, Mapping, Sequence, TypeVar, Union as _UnionT, overload +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from typing import Any, ClassVar, Generic, TypeVar, Union as _UnionT, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -84,8 +86,8 @@ class _CData(metaclass=_CDataMeta): class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[type[_CData] | None, _FuncPointer, tuple[_CData, ...]], _CData] -_PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] +_ECT: TypeAlias = Callable[[type[_CData] | None, _FuncPointer, tuple[_CData, ...]], _CData] +_PF: TypeAlias = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): restype: type[_CData] | Callable[[int], Any] | None @@ -121,12 +123,12 @@ class _CArgObject: ... # Any type that can be implicitly converted to c_void_p when passed as a C function argument. # (bytes is not included here, see below.) -_CVoidPLike = _PointerLike | Array[Any] | _CArgObject | int +_CVoidPLike: TypeAlias = _PointerLike | Array[Any] | _CArgObject | int # Same as above, but including types known to be read-only (i. e. bytes). # This distinction is not strictly necessary (ctypes doesn't differentiate between const # and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) # when memmove(buf, b'foo', 4) was intended. -_CVoidConstPLike = _CVoidPLike | bytes +_CVoidConstPLike: TypeAlias = _CVoidPLike | bytes def addressof(obj: _CData) -> int: ... def alignment(obj_or_type: _CData | type[_CData]) -> int: ... diff --git a/mypy/typeshed/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi index c178a9bdf936..9536114b786a 100644 --- a/mypy/typeshed/stdlib/ctypes/wintypes.pyi +++ b/mypy/typeshed/stdlib/ctypes/wintypes.pyi @@ -20,6 +20,7 @@ from ctypes import ( c_wchar_p, pointer, ) +from typing_extensions import TypeAlias BYTE = c_byte WORD = c_ushort @@ -182,53 +183,53 @@ class WIN32_FIND_DATAW(Structure): # These pointer type definitions use pointer[...] instead of POINTER(...), to allow them # to be used in type annotations. -PBOOL = pointer[BOOL] -LPBOOL = pointer[BOOL] -PBOOLEAN = pointer[BOOLEAN] -PBYTE = pointer[BYTE] -LPBYTE = pointer[BYTE] -PCHAR = pointer[CHAR] -LPCOLORREF = pointer[COLORREF] -PDWORD = pointer[DWORD] -LPDWORD = pointer[DWORD] -PFILETIME = pointer[FILETIME] -LPFILETIME = pointer[FILETIME] -PFLOAT = pointer[FLOAT] -PHANDLE = pointer[HANDLE] -LPHANDLE = pointer[HANDLE] -PHKEY = pointer[HKEY] -LPHKL = pointer[HKL] -PINT = pointer[INT] -LPINT = pointer[INT] -PLARGE_INTEGER = pointer[LARGE_INTEGER] -PLCID = pointer[LCID] -PLONG = pointer[LONG] -LPLONG = pointer[LONG] -PMSG = pointer[MSG] -LPMSG = pointer[MSG] -PPOINT = pointer[POINT] -LPPOINT = pointer[POINT] -PPOINTL = pointer[POINTL] -PRECT = pointer[RECT] -LPRECT = pointer[RECT] -PRECTL = pointer[RECTL] -LPRECTL = pointer[RECTL] -LPSC_HANDLE = pointer[SC_HANDLE] -PSHORT = pointer[SHORT] -PSIZE = pointer[SIZE] -LPSIZE = pointer[SIZE] -PSIZEL = pointer[SIZEL] -LPSIZEL = pointer[SIZEL] -PSMALL_RECT = pointer[SMALL_RECT] -PUINT = pointer[UINT] -LPUINT = pointer[UINT] -PULARGE_INTEGER = pointer[ULARGE_INTEGER] -PULONG = pointer[ULONG] -PUSHORT = pointer[USHORT] -PWCHAR = pointer[WCHAR] -PWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] -LPWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] -PWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] -LPWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] -PWORD = pointer[WORD] -LPWORD = pointer[WORD] +PBOOL: TypeAlias = pointer[BOOL] +LPBOOL: TypeAlias = pointer[BOOL] +PBOOLEAN: TypeAlias = pointer[BOOLEAN] +PBYTE: TypeAlias = pointer[BYTE] +LPBYTE: TypeAlias = pointer[BYTE] +PCHAR: TypeAlias = pointer[CHAR] +LPCOLORREF: TypeAlias = pointer[COLORREF] +PDWORD: TypeAlias = pointer[DWORD] +LPDWORD: TypeAlias = pointer[DWORD] +PFILETIME: TypeAlias = pointer[FILETIME] +LPFILETIME: TypeAlias = pointer[FILETIME] +PFLOAT: TypeAlias = pointer[FLOAT] +PHANDLE: TypeAlias = pointer[HANDLE] +LPHANDLE: TypeAlias = pointer[HANDLE] +PHKEY: TypeAlias = pointer[HKEY] +LPHKL: TypeAlias = pointer[HKL] +PINT: TypeAlias = pointer[INT] +LPINT: TypeAlias = pointer[INT] +PLARGE_INTEGER: TypeAlias = pointer[LARGE_INTEGER] +PLCID: TypeAlias = pointer[LCID] +PLONG: TypeAlias = pointer[LONG] +LPLONG: TypeAlias = pointer[LONG] +PMSG: TypeAlias = pointer[MSG] +LPMSG: TypeAlias = pointer[MSG] +PPOINT: TypeAlias = pointer[POINT] +LPPOINT: TypeAlias = pointer[POINT] +PPOINTL: TypeAlias = pointer[POINTL] +PRECT: TypeAlias = pointer[RECT] +LPRECT: TypeAlias = pointer[RECT] +PRECTL: TypeAlias = pointer[RECTL] +LPRECTL: TypeAlias = pointer[RECTL] +LPSC_HANDLE: TypeAlias = pointer[SC_HANDLE] +PSHORT: TypeAlias = pointer[SHORT] +PSIZE: TypeAlias = pointer[SIZE] +LPSIZE: TypeAlias = pointer[SIZE] +PSIZEL: TypeAlias = pointer[SIZEL] +LPSIZEL: TypeAlias = pointer[SIZEL] +PSMALL_RECT: TypeAlias = pointer[SMALL_RECT] +PUINT: TypeAlias = pointer[UINT] +LPUINT: TypeAlias = pointer[UINT] +PULARGE_INTEGER: TypeAlias = pointer[ULARGE_INTEGER] +PULONG: TypeAlias = pointer[ULONG] +PUSHORT: TypeAlias = pointer[USHORT] +PWCHAR: TypeAlias = pointer[WCHAR] +PWIN32_FIND_DATAA: TypeAlias = pointer[WIN32_FIND_DATAA] +LPWIN32_FIND_DATAA: TypeAlias = pointer[WIN32_FIND_DATAA] +PWIN32_FIND_DATAW: TypeAlias = pointer[WIN32_FIND_DATAW] +LPWIN32_FIND_DATAW: TypeAlias = pointer[WIN32_FIND_DATAW] +PWORD: TypeAlias = pointer[WORD] +LPWORD: TypeAlias = pointer[WORD] diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index ee74c13b6b50..f80ed442ea9c 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Callable, TypeVar +from collections.abc import Callable +from typing import Any, TypeVar if sys.platform != "win32": from _curses import * diff --git a/mypy/typeshed/stdlib/curses/textpad.pyi b/mypy/typeshed/stdlib/curses/textpad.pyi index b8a9c843f402..ad9983431fc7 100644 --- a/mypy/typeshed/stdlib/curses/textpad.pyi +++ b/mypy/typeshed/stdlib/curses/textpad.pyi @@ -1,5 +1,5 @@ import sys -from typing import Callable +from collections.abc import Callable if sys.platform != "win32": from _curses import _CursesWindow diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index d82e9a2bb526..f58c6f9f1460 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -2,7 +2,8 @@ import enum import sys import types from builtins import type as Type # alias to avoid name clashes with fields named "type" -from typing import Any, Callable, Generic, Iterable, Mapping, Protocol, TypeVar, overload +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Generic, Protocol, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 220e07e25fe0..113c679743fd 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self from time import struct_time from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, TypeVar, overload -from typing_extensions import Literal, final +from typing_extensions import Literal, TypeAlias, final if sys.version_info >= (3, 9): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") @@ -19,7 +19,7 @@ class tzinfo: def fromutc(self, __dt: datetime) -> datetime: ... # Alias required to avoid name conflicts with date(time).tzinfo. -_tzinfo = tzinfo +_tzinfo: TypeAlias = tzinfo @final class timezone(tzinfo): @@ -150,8 +150,8 @@ class time: fold: int = ..., ) -> Self: ... -_date = date -_time = time +_date: TypeAlias = date +_time: TypeAlias = time class timedelta(SupportsAbs[timedelta]): min: ClassVar[timedelta] diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index d43a2415caff..9e99f0d5e74c 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,13 +1,13 @@ from _typeshed import Self +from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing import Iterator, MutableMapping -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["open", "whichdb", "error"] -_KeyType = str | bytes -_ValueType = str | bytes -_TFlags = Literal[ +_KeyType: TypeAlias = str | bytes +_ValueType: TypeAlias = str | bytes +_TFlags: TypeAlias = Literal[ "r", "w", "c", diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index 5af95ace72ad..4fd199f19728 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -1,11 +1,12 @@ from _typeshed import Self +from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing import Iterator, MutableMapping +from typing_extensions import TypeAlias __all__ = ["error", "open"] -_KeyType = str | bytes -_ValueType = str | bytes +_KeyType: TypeAlias = str | bytes +_ValueType: TypeAlias = str | bytes error = OSError diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 9a603228a691..561206c4e0be 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -2,11 +2,12 @@ import sys from _typeshed import Self from types import TracebackType from typing import TypeVar, overload +from typing_extensions import TypeAlias if sys.platform != "win32": _T = TypeVar("_T") - _KeyType = str | bytes - _ValueType = str | bytes + _KeyType: TypeAlias = str | bytes + _ValueType: TypeAlias = str | bytes open_flags: str diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index 8405bec2bcf2..f1032bf3cae7 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -2,11 +2,12 @@ import sys from _typeshed import Self from types import TracebackType from typing import TypeVar, overload +from typing_extensions import TypeAlias if sys.platform != "win32": _T = TypeVar("_T") - _KeyType = str | bytes - _ValueType = str | bytes + _KeyType: TypeAlias = str | bytes + _ValueType: TypeAlias = str | bytes class error(OSError): ... library: str diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index 819ed1641448..35fc4405f11b 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -1,262 +1,2 @@ -import numbers -import sys -from _typeshed import Self -from types import TracebackType -from typing import Any, Container, NamedTuple, Sequence, Union, overload - -_Decimal = Decimal | int -_DecimalNew = Union[Decimal, float, str, tuple[int, Sequence[int], int]] -_ComparableNum = Decimal | float | numbers.Rational - -__libmpdec_version__: str - -class DecimalTuple(NamedTuple): - sign: int - digits: tuple[int, ...] - exponent: int - -ROUND_DOWN: str -ROUND_HALF_UP: str -ROUND_HALF_EVEN: str -ROUND_CEILING: str -ROUND_FLOOR: str -ROUND_UP: str -ROUND_HALF_DOWN: str -ROUND_05UP: str - -if sys.version_info >= (3, 7): - HAVE_CONTEXTVAR: bool -HAVE_THREADS: bool -MAX_EMAX: int -MAX_PREC: int -MIN_EMIN: int -MIN_ETINY: int - -class DecimalException(ArithmeticError): ... -class Clamped(DecimalException): ... -class InvalidOperation(DecimalException): ... -class ConversionSyntax(InvalidOperation): ... -class DivisionByZero(DecimalException, ZeroDivisionError): ... -class DivisionImpossible(InvalidOperation): ... -class DivisionUndefined(InvalidOperation, ZeroDivisionError): ... -class Inexact(DecimalException): ... -class InvalidContext(InvalidOperation): ... -class Rounded(DecimalException): ... -class Subnormal(DecimalException): ... -class Overflow(Inexact, Rounded): ... -class Underflow(Inexact, Rounded, Subnormal): ... -class FloatOperation(DecimalException, TypeError): ... - -def setcontext(__context: Context) -> None: ... -def getcontext() -> Context: ... -def localcontext(ctx: Context | None = ...) -> _ContextManager: ... - -class Decimal: - def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... - @classmethod - def from_float(cls: type[Self], __f: float) -> Self: ... - def __bool__(self) -> bool: ... - def compare(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __hash__(self) -> int: ... - def as_tuple(self) -> DecimalTuple: ... - def as_integer_ratio(self) -> tuple[int, int]: ... - def to_eng_string(self, context: Context | None = ...) -> str: ... - def __abs__(self) -> Decimal: ... - def __add__(self, __other: _Decimal) -> Decimal: ... - def __divmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... - def __eq__(self, __other: object) -> bool: ... - def __floordiv__(self, __other: _Decimal) -> Decimal: ... - def __ge__(self, __other: _ComparableNum) -> bool: ... - def __gt__(self, __other: _ComparableNum) -> bool: ... - def __le__(self, __other: _ComparableNum) -> bool: ... - def __lt__(self, __other: _ComparableNum) -> bool: ... - def __mod__(self, __other: _Decimal) -> Decimal: ... - def __mul__(self, __other: _Decimal) -> Decimal: ... - def __neg__(self) -> Decimal: ... - def __pos__(self) -> Decimal: ... - def __pow__(self, __other: _Decimal, __modulo: _Decimal | None = ...) -> Decimal: ... - def __radd__(self, __other: _Decimal) -> Decimal: ... - def __rdivmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, __other: _Decimal) -> Decimal: ... - def __rmod__(self, __other: _Decimal) -> Decimal: ... - def __rmul__(self, __other: _Decimal) -> Decimal: ... - def __rsub__(self, __other: _Decimal) -> Decimal: ... - def __rtruediv__(self, __other: _Decimal) -> Decimal: ... - def __sub__(self, __other: _Decimal) -> Decimal: ... - def __truediv__(self, __other: _Decimal) -> Decimal: ... - def remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __float__(self) -> float: ... - def __int__(self) -> int: ... - def __trunc__(self) -> int: ... - @property - def real(self) -> Decimal: ... - @property - def imag(self) -> Decimal: ... - def conjugate(self) -> Decimal: ... - def __complex__(self) -> complex: ... - @overload - def __round__(self) -> int: ... - @overload - def __round__(self, __ndigits: int) -> Decimal: ... - def __floor__(self) -> int: ... - def __ceil__(self) -> int: ... - def fma(self, other: _Decimal, third: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rpow__(self, __other: _Decimal, __context: Context | None = ...) -> Decimal: ... - def normalize(self, context: Context | None = ...) -> Decimal: ... - def quantize(self, exp: _Decimal, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def same_quantum(self, other: _Decimal, context: Context | None = ...) -> bool: ... - def to_integral_exact(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def to_integral_value(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def to_integral(self, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... - def sqrt(self, context: Context | None = ...) -> Decimal: ... - def max(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def min(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def adjusted(self) -> int: ... - def canonical(self) -> Decimal: ... - def compare_signal(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def compare_total(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def compare_total_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def copy_abs(self) -> Decimal: ... - def copy_negate(self) -> Decimal: ... - def copy_sign(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def exp(self, context: Context | None = ...) -> Decimal: ... - def is_canonical(self) -> bool: ... - def is_finite(self) -> bool: ... - def is_infinite(self) -> bool: ... - def is_nan(self) -> bool: ... - def is_normal(self, context: Context | None = ...) -> bool: ... - def is_qnan(self) -> bool: ... - def is_signed(self) -> bool: ... - def is_snan(self) -> bool: ... - def is_subnormal(self, context: Context | None = ...) -> bool: ... - def is_zero(self) -> bool: ... - def ln(self, context: Context | None = ...) -> Decimal: ... - def log10(self, context: Context | None = ...) -> Decimal: ... - def logb(self, context: Context | None = ...) -> Decimal: ... - def logical_and(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def logical_invert(self, context: Context | None = ...) -> Decimal: ... - def logical_or(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def logical_xor(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def max_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def min_mag(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def next_minus(self, context: Context | None = ...) -> Decimal: ... - def next_plus(self, context: Context | None = ...) -> Decimal: ... - def next_toward(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def number_class(self, context: Context | None = ...) -> str: ... - def radix(self) -> Decimal: ... - def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self: Self) -> tuple[type[Self], tuple[str]]: ... - def __copy__(self: Self) -> Self: ... - def __deepcopy__(self: Self, __memo: Any) -> Self: ... - def __format__(self, __specifier: str, __context: Context | None = ...) -> str: ... - -class _ContextManager: - new_context: Context - saved_context: Context - def __init__(self, new_context: Context) -> None: ... - def __enter__(self) -> Context: ... - def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... - -_TrapType = type[DecimalException] - -class Context: - prec: int - rounding: str - Emin: int - Emax: int - capitals: int - clamp: int - traps: dict[_TrapType, bool] - flags: dict[_TrapType, bool] - def __init__( - self, - prec: int | None = ..., - rounding: str | None = ..., - Emin: int | None = ..., - Emax: int | None = ..., - capitals: int | None = ..., - clamp: int | None = ..., - flags: None | dict[_TrapType, bool] | Container[_TrapType] = ..., - traps: None | dict[_TrapType, bool] | Container[_TrapType] = ..., - _ignored_flags: list[_TrapType] | None = ..., - ) -> None: ... - # __setattr__() only allows to set a specific set of attributes, - # already defined above. - def __delattr__(self, __name: str) -> None: ... - def __reduce__(self: Self) -> tuple[type[Self], tuple[Any, ...]]: ... - def clear_flags(self) -> None: ... - def clear_traps(self) -> None: ... - def copy(self) -> Context: ... - def __copy__(self) -> Context: ... - __hash__: Any - def Etiny(self) -> int: ... - def Etop(self) -> int: ... - def create_decimal(self, __num: _DecimalNew = ...) -> Decimal: ... - def create_decimal_from_float(self, __f: float) -> Decimal: ... - def abs(self, __x: _Decimal) -> Decimal: ... - def add(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def canonical(self, __x: Decimal) -> Decimal: ... - def compare(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_signal(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def compare_total_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def copy_abs(self, __x: _Decimal) -> Decimal: ... - def copy_decimal(self, __x: _Decimal) -> Decimal: ... - def copy_negate(self, __x: _Decimal) -> Decimal: ... - def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divmod(self, __x: _Decimal, __y: _Decimal) -> tuple[Decimal, Decimal]: ... - def exp(self, __x: _Decimal) -> Decimal: ... - def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... - def is_canonical(self, __x: _Decimal) -> bool: ... - def is_finite(self, __x: _Decimal) -> bool: ... - def is_infinite(self, __x: _Decimal) -> bool: ... - def is_nan(self, __x: _Decimal) -> bool: ... - def is_normal(self, __x: _Decimal) -> bool: ... - def is_qnan(self, __x: _Decimal) -> bool: ... - def is_signed(self, __x: _Decimal) -> bool: ... - def is_snan(self, __x: _Decimal) -> bool: ... - def is_subnormal(self, __x: _Decimal) -> bool: ... - def is_zero(self, __x: _Decimal) -> bool: ... - def ln(self, __x: _Decimal) -> Decimal: ... - def log10(self, __x: _Decimal) -> Decimal: ... - def logb(self, __x: _Decimal) -> Decimal: ... - def logical_and(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_invert(self, __x: _Decimal) -> Decimal: ... - def logical_or(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def logical_xor(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def max_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def min_mag(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def minus(self, __x: _Decimal) -> Decimal: ... - def multiply(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def next_minus(self, __x: _Decimal) -> Decimal: ... - def next_plus(self, __x: _Decimal) -> Decimal: ... - def next_toward(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def normalize(self, __x: _Decimal) -> Decimal: ... - def number_class(self, __x: _Decimal) -> str: ... - def plus(self, __x: _Decimal) -> Decimal: ... - def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = ...) -> Decimal: ... - def quantize(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def radix(self) -> Decimal: ... - def remainder(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def remainder_near(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def rotate(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def same_quantum(self, __x: _Decimal, __y: _Decimal) -> bool: ... - def scaleb(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def shift(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def sqrt(self, __x: _Decimal) -> Decimal: ... - def subtract(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def to_eng_string(self, __x: _Decimal) -> str: ... - def to_sci_string(self, __x: _Decimal) -> str: ... - def to_integral_exact(self, __x: _Decimal) -> Decimal: ... - def to_integral_value(self, __x: _Decimal) -> Decimal: ... - def to_integral(self, __x: _Decimal) -> Decimal: ... - -DefaultContext: Context -BasicContext: Context -ExtendedContext: Context +from _decimal import * +from _decimal import __libmpdec_version__ as __libmpdec_version__, __version__ as __version__ diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index a572430155e9..87e3768034bf 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, overload +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, AnyStr, Generic, NamedTuple, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index 910458c08e00..9a99d4498668 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -1,8 +1,10 @@ import sys import types from _typeshed import Self +from collections.abc import Callable, Iterator from opcode import * # `dis` re-exports it as a part of public API -from typing import IO, Any, Callable, Iterator, NamedTuple +from typing import IO, Any, NamedTuple +from typing_extensions import TypeAlias __all__ = [ "code_info", @@ -34,28 +36,63 @@ __all__ = [ # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_HaveCodeType = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] -_HaveCodeOrStringType = _HaveCodeType | str | bytes +_HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_HaveCodeOrStringType: TypeAlias = _HaveCodeType | str | bytes -class Instruction(NamedTuple): - opname: str - opcode: int - arg: int | None - argval: Any - argrepr: str - offset: int - starts_line: int | None - is_jump_target: bool +if sys.version_info >= (3, 11): + class Positions(NamedTuple): + lineno: int | None = ... + end_lineno: int | None = ... + col_offset: int | None = ... + end_col_offset: int | None = ... + +if sys.version_info >= (3, 11): + class Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + starts_line: int | None + is_jump_target: bool + positions: Positions | None = ... + +else: + class Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + starts_line: int | None + is_jump_target: bool class Bytecode: codeobj: types.CodeType first_line: int - def __init__(self, x: _HaveCodeOrStringType, *, first_line: int | None = ..., current_offset: int | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__( + self, + x: _HaveCodeOrStringType, + *, + first_line: int | None = ..., + current_offset: int | None = ..., + show_caches: bool = ..., + ) -> None: ... + @classmethod + def from_traceback(cls: type[Self], tb: types.TracebackType, *, show_caches: bool = ...) -> Self: ... + else: + def __init__( + self, x: _HaveCodeOrStringType, *, first_line: int | None = ..., current_offset: int | None = ... + ) -> None: ... + @classmethod + def from_traceback(cls: type[Self], tb: types.TracebackType) -> Self: ... + def __iter__(self) -> Iterator[Instruction]: ... def info(self) -> str: ... def dis(self) -> str: ... - @classmethod - def from_traceback(cls: type[Self], tb: types.TracebackType) -> Self: ... COMPILER_FLAG_NAMES: dict[int, str] @@ -64,14 +101,27 @@ def findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]: ... def pretty_flags(flags: int) -> str: ... def code_info(x: _HaveCodeOrStringType) -> str: ... -if sys.version_info >= (3, 7): +if sys.version_info >= (3, 11): + def dis( + x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ..., depth: int | None = ..., show_caches: bool = ... + ) -> None: ... + +elif sys.version_info >= (3, 7): def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ..., depth: int | None = ...) -> None: ... else: def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ...) -> None: ... -def distb(tb: types.TracebackType | None = ..., *, file: IO[str] | None = ...) -> None: ... -def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... -def disco(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... +if sys.version_info >= (3, 11): + def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ..., show_caches: bool = ...) -> None: ... + def disco(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ..., show_caches: bool = ...) -> None: ... + def distb(tb: types.TracebackType | None = ..., *, file: IO[str] | None = ..., show_caches: bool = ...) -> None: ... + def get_instructions(x: _HaveCodeType, *, first_line: int | None = ..., show_caches: bool = ...) -> Iterator[Instruction]: ... + +else: + def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... + def disco(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... + def distb(tb: types.TracebackType | None = ..., *, file: IO[str] | None = ...) -> None: ... + def get_instructions(x: _HaveCodeType, *, first_line: int | None = ...) -> Iterator[Instruction]: ... + def show_code(co: _HaveCodeType, *, file: IO[str] | None = ...) -> None: ... -def get_instructions(x: _HaveCodeType, *, first_line: int | None = ...) -> Iterator[Instruction]: ... diff --git a/mypy/typeshed/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi index 4cdc62ce3bae..ed823f7c070f 100644 --- a/mypy/typeshed/stdlib/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/ccompiler.pyi @@ -1,6 +1,8 @@ -from typing import Any, Callable, Union +from collections.abc import Callable +from typing import Any, Union +from typing_extensions import TypeAlias -_Macro = Union[tuple[str], tuple[str, str | None]] +_Macro: TypeAlias = Union[tuple[str], tuple[str, str | None]] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] diff --git a/mypy/typeshed/stdlib/distutils/cmd.pyi b/mypy/typeshed/stdlib/distutils/cmd.pyi index 96a048c93f41..8163ae78fd8f 100644 --- a/mypy/typeshed/stdlib/distutils/cmd.pyi +++ b/mypy/typeshed/stdlib/distutils/cmd.pyi @@ -1,6 +1,7 @@ from abc import abstractmethod +from collections.abc import Callable, Iterable from distutils.dist import Distribution -from typing import Any, Callable, Iterable +from typing import Any class Command: sub_commands: list[tuple[str, Callable[[Command], bool] | None]] diff --git a/mypy/typeshed/stdlib/distutils/core.pyi b/mypy/typeshed/stdlib/distutils/core.pyi index 6564c9a86ded..199a4d70a953 100644 --- a/mypy/typeshed/stdlib/distutils/core.pyi +++ b/mypy/typeshed/stdlib/distutils/core.pyi @@ -1,7 +1,8 @@ +from collections.abc import Mapping from distutils.cmd import Command as Command from distutils.dist import Distribution as Distribution from distutils.extension import Extension as Extension -from typing import Any, Mapping +from typing import Any def setup( *, diff --git a/mypy/typeshed/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi index c5b3afe7cc3b..ef47e4e4d15a 100644 --- a/mypy/typeshed/stdlib/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/distutils/dist.pyi @@ -1,6 +1,7 @@ from _typeshed import StrOrBytesPath, SupportsWrite +from collections.abc import Iterable, Mapping from distutils.cmd import Command -from typing import IO, Any, Iterable, Mapping +from typing import IO, Any class DistributionMetadata: def __init__(self, path: int | StrOrBytesPath | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index c2a5bd4c20a1..6a7124bd15ad 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -1,7 +1,9 @@ -from typing import Any, Iterable, Mapping, overload +from collections.abc import Iterable, Mapping +from typing import Any, overload +from typing_extensions import TypeAlias -_Option = tuple[str, str | None, str] -_GR = tuple[list[str], OptionDummy] +_Option: TypeAlias = tuple[str, str | None, str] +_GR: TypeAlias = tuple[list[str], OptionDummy] def fancy_getopt( options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: list[str] | None diff --git a/mypy/typeshed/stdlib/distutils/file_util.pyi b/mypy/typeshed/stdlib/distutils/file_util.pyi index a7f24105a678..b3127841bce8 100644 --- a/mypy/typeshed/stdlib/distutils/file_util.pyi +++ b/mypy/typeshed/stdlib/distutils/file_util.pyi @@ -1,4 +1,4 @@ -from typing import Sequence +from collections.abc import Sequence def copy_file( src: str, diff --git a/mypy/typeshed/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi index 2b436938f13e..361cb13f0c47 100644 --- a/mypy/typeshed/stdlib/distutils/filelist.pyi +++ b/mypy/typeshed/stdlib/distutils/filelist.pyi @@ -1,4 +1,5 @@ -from typing import Iterable, Pattern, overload +from collections.abc import Iterable +from typing import Pattern, overload from typing_extensions import Literal # class is entirely undocumented diff --git a/mypy/typeshed/stdlib/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/distutils/sysconfig.pyi index 3f579be40882..bf7db9c8f06b 100644 --- a/mypy/typeshed/stdlib/distutils/sysconfig.pyi +++ b/mypy/typeshed/stdlib/distutils/sysconfig.pyi @@ -1,5 +1,5 @@ +from collections.abc import Mapping from distutils.ccompiler import CCompiler -from typing import Mapping PREFIX: str EXEC_PREFIX: str diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 651e1b298aaf..c767436c2be8 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -1,6 +1,9 @@ import types import unittest -from typing import Any, Callable, NamedTuple +from _typeshed import ExcInfo +from collections.abc import Callable +from typing import Any, NamedTuple +from typing_extensions import TypeAlias __all__ = [ "register_optionflag", @@ -123,8 +126,7 @@ class DocTestFinder: extraglobs: dict[str, Any] | None = ..., ) -> list[DocTest]: ... -_Out = Callable[[str], Any] -_ExcInfo = tuple[type[BaseException], BaseException, types.TracebackType] +_Out: TypeAlias = Callable[[str], Any] class DocTestRunner: DIVIDER: str @@ -137,7 +139,7 @@ class DocTestRunner: def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ... def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... - def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... def run( self, test: DocTest, compileflags: int | None = ..., out: _Out | None = ..., clear_globs: bool = ... ) -> TestResults: ... @@ -157,8 +159,8 @@ class DocTestFailure(Exception): class UnexpectedException(Exception): test: DocTest example: Example - exc_info: _ExcInfo - def __init__(self, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + exc_info: ExcInfo + def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... class DebugRunner(DocTestRunner): ... diff --git a/mypy/typeshed/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi index 49e18ccb8c2e..78368a2cf4a0 100644 --- a/mypy/typeshed/stdlib/email/__init__.pyi +++ b/mypy/typeshed/stdlib/email/__init__.pyi @@ -1,11 +1,12 @@ +from collections.abc import Callable from email.message import Message from email.policy import Policy -from typing import IO, Callable, TypeVar, Union +from typing import IO, Union +from typing_extensions import TypeAlias # Definitions imported by multiple submodules in typeshed -_MessageT = TypeVar("_MessageT", bound=Message) # noqa: Y018 -_ParamType = Union[str, tuple[str | None, str | None, str]] -_ParamsType = Union[str, None, tuple[str, str | None, str]] +_ParamType: TypeAlias = Union[str, tuple[str | None, str | None, str]] +_ParamsType: TypeAlias = Union[str, None, tuple[str, str | None, str]] def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index 749b6454a8f8..abe6ec63abb1 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import Self +from collections.abc import Iterable, Iterator from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, Pattern +from typing import Any, Pattern from typing_extensions import Final WSP: Final[set[str]] diff --git a/mypy/typeshed/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi index fd3de9ceace2..236908537f83 100644 --- a/mypy/typeshed/stdlib/email/charset.pyi +++ b/mypy/typeshed/stdlib/email/charset.pyi @@ -1,4 +1,4 @@ -from typing import Iterator +from collections.abc import Iterator __all__ = ["Charset", "add_alias", "add_charset", "add_codec"] diff --git a/mypy/typeshed/stdlib/email/contentmanager.pyi b/mypy/typeshed/stdlib/email/contentmanager.pyi index 68fe99c8c09f..3ac665eaa7bf 100644 --- a/mypy/typeshed/stdlib/email/contentmanager.pyi +++ b/mypy/typeshed/stdlib/email/contentmanager.pyi @@ -1,5 +1,6 @@ +from collections.abc import Callable from email.message import Message -from typing import Any, Callable +from typing import Any class ContentManager: def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/email/feedparser.pyi b/mypy/typeshed/stdlib/email/feedparser.pyi index b1c7e0f7d127..c535c353daad 100644 --- a/mypy/typeshed/stdlib/email/feedparser.pyi +++ b/mypy/typeshed/stdlib/email/feedparser.pyi @@ -1,10 +1,12 @@ -from email import _MessageT +from collections.abc import Callable from email.message import Message from email.policy import Policy -from typing import Callable, Generic, overload +from typing import Generic, TypeVar, overload __all__ = ["FeedParser", "BytesFeedParser"] +_MessageT = TypeVar("_MessageT", bound=Message) + class FeedParser(Generic[_MessageT]): @overload def __init__(self: FeedParser[Message], _factory: None = ..., *, policy: Policy = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/iterators.pyi b/mypy/typeshed/stdlib/email/iterators.pyi index ad5517712d25..29068819ac15 100644 --- a/mypy/typeshed/stdlib/email/iterators.pyi +++ b/mypy/typeshed/stdlib/email/iterators.pyi @@ -1,6 +1,6 @@ from _typeshed import SupportsWrite +from collections.abc import Iterator from email.message import Message -from typing import Iterator __all__ = ["body_line_iterator", "typed_subpart_iterator", "walk"] diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 97de1cf5daf6..6544f8fc2385 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -1,17 +1,19 @@ +from collections.abc import Generator, Iterator, Sequence from email import _ParamsType, _ParamType from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Generator, Iterator, Sequence, TypeVar +from typing import Any, TypeVar +from typing_extensions import TypeAlias __all__ = ["Message", "EmailMessage"] _T = TypeVar("_T") -_PayloadType = list[Message] | str | bytes -_CharsetType = Charset | str | None -_HeaderType = Any +_PayloadType: TypeAlias = list[Message] | str | bytes +_CharsetType: TypeAlias = Charset | str | None +_HeaderType: TypeAlias = Any class Message: policy: Policy # undocumented diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index 1846bdcc36b2..dcd346c1b46d 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -1,14 +1,11 @@ -import email.feedparser -from email import _MessageT +from collections.abc import Callable +from email.feedparser import BytesFeedParser as BytesFeedParser, FeedParser as FeedParser from email.message import Message from email.policy import Policy -from typing import BinaryIO, Callable, TextIO +from typing import BinaryIO, TextIO __all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedParser", "BytesFeedParser"] -FeedParser = email.feedparser.FeedParser[_MessageT] -BytesFeedParser = email.feedparser.BytesFeedParser[_MessageT] - class Parser: def __init__(self, _class: Callable[[], Message] | None = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index d4ebb1fd5e37..4df3c1e48b07 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -1,9 +1,10 @@ from abc import ABCMeta, abstractmethod +from collections.abc import Callable from email.contentmanager import ContentManager from email.errors import MessageDefect from email.header import Header from email.message import Message -from typing import Any, Callable +from typing import Any __all__ = ["Compat32", "compat32", "Policy", "EmailPolicy", "default", "strict", "SMTP", "HTTP"] diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index aeffb0ef1981..480c5f79549d 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -3,6 +3,7 @@ import sys from email import _ParamType from email.charset import Charset from typing import overload +from typing_extensions import TypeAlias __all__ = [ "collapse_rfc2231_value", @@ -22,7 +23,7 @@ __all__ = [ "unquote", ] -_PDTZ = tuple[int, int, int, int, int, int, int, int, int, int | None] +_PDTZ: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int | None] def quote(str: str) -> str: ... def unquote(str: str) -> str: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index f49bcd7a00e0..a7c84c5b1c0d 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -5,7 +5,7 @@ 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_extensions import Literal +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 11): __all__ = [ @@ -52,7 +52,7 @@ _EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) # # >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2}) # -_EnumNames = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] +_EnumNames: TypeAlias = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] class _EnumDict(dict[str, Any]): def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/errno.pyi b/mypy/typeshed/stdlib/errno.pyi index 12410af23e71..9ef1fe6e7618 100644 --- a/mypy/typeshed/stdlib/errno.pyi +++ b/mypy/typeshed/stdlib/errno.pyi @@ -1,4 +1,4 @@ -from typing import Mapping +from collections.abc import Mapping errorcode: Mapping[int, str] diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index 7c606af40791..a6747dd504a3 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterable, Sequence from os import PathLike -from typing import Any, AnyStr, Callable, Generic, Iterable, Sequence +from typing import Any, AnyStr, Generic from typing_extensions import Literal if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index a3b62948ca20..0ef8c14ddaac 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Self, StrOrBytesPath +from collections.abc import Callable, Iterable, Iterator from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator +from typing import IO, Any, AnyStr, Generic __all__ = [ "input", diff --git a/mypy/typeshed/stdlib/fnmatch.pyi b/mypy/typeshed/stdlib/fnmatch.pyi index 8351fce59ebb..7051c999c430 100644 --- a/mypy/typeshed/stdlib/fnmatch.pyi +++ b/mypy/typeshed/stdlib/fnmatch.pyi @@ -1,4 +1,5 @@ -from typing import AnyStr, Iterable +from collections.abc import Iterable +from typing import AnyStr __all__ = ["filter", "fnmatch", "fnmatchcase", "translate"] diff --git a/mypy/typeshed/stdlib/formatter.pyi b/mypy/typeshed/stdlib/formatter.pyi index f5d8348d08a1..0aac0a5f918c 100644 --- a/mypy/typeshed/stdlib/formatter.pyi +++ b/mypy/typeshed/stdlib/formatter.pyi @@ -1,8 +1,10 @@ -from typing import IO, Any, Iterable +from collections.abc import Iterable +from typing import IO, Any +from typing_extensions import TypeAlias AS_IS: None -_FontType = tuple[str, bool, bool, bool] -_StylesType = tuple[Any, ...] +_FontType: TypeAlias = tuple[str, bool, bool, bool] +_StylesType: TypeAlias = tuple[Any, ...] class NullFormatter: writer: NullWriter | None diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 00989fb1fc02..0d787a011f5b 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -3,9 +3,9 @@ from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real from typing import Any, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias -_ComparableNum = int | float | Decimal | Real +_ComparableNum: TypeAlias = int | float | Decimal | Real if sys.version_info >= (3, 9): __all__ = ["Fraction"] diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 4a5dad0dd14f..925ad5884700 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import Self, SupportsRead, SupportsReadline +from collections.abc import Callable, Iterable, Iterator from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Callable, Iterable, Iterator, TextIO +from typing import Any, TextIO from typing_extensions import Literal __all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors", "FTP_TLS"] diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 741a53ed82a2..44feeed63f6a 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,8 +1,9 @@ import sys import types from _typeshed import Self, SupportsAllComparisons, SupportsItems -from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, TypeVar, overload -from typing_extensions import Literal, final +from collections.abc import Callable, Hashable, Iterable, Sequence, Sized +from typing import Any, Generic, NamedTuple, TypeVar, overload +from typing_extensions import Literal, TypeAlias, final if sys.version_info >= (3, 9): from types import GenericAlias @@ -54,7 +55,7 @@ else: "singledispatch", ] -_AnyCallable = Callable[..., Any] +_AnyCallable: TypeAlias = Callable[..., Any] _T = TypeVar("_T") _S = TypeVar("_S") @@ -111,7 +112,7 @@ class partial(Generic[_T]): def __class_getitem__(cls, item: Any) -> GenericAlias: ... # With protocols, this could change into a generic protocol that defines __get__ and returns _T -_Descriptor = Any +_Descriptor: TypeAlias = Any class partialmethod(Generic[_T]): func: Callable[..., _T] | _Descriptor diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 7c15e0f5b0a2..98b92e109f82 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,6 +1,7 @@ import sys -from typing import Any, Callable -from typing_extensions import Literal +from collections.abc import Callable +from typing import Any +from typing_extensions import Literal, TypeAlias DEBUG_COLLECTABLE: Literal[2] DEBUG_LEAK: Literal[38] @@ -8,7 +9,7 @@ DEBUG_SAVEALL: Literal[32] DEBUG_STATS: Literal[1] DEBUG_UNCOLLECTABLE: Literal[4] -_CallbackType = Callable[[Literal["start", "stop"], dict[str, int]], object] +_CallbackType: TypeAlias = Callable[[Literal["start", "stop"], dict[str, int]], object] callbacks: list[_CallbackType] garbage: list[Any] diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index 3abedda262ea..984d0c3cf51e 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -1,6 +1,7 @@ import os from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRichComparisonT -from typing import Sequence, overload +from collections.abc import Sequence +from typing import overload from typing_extensions import Literal __all__ = [ diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index 1f3ef67ab0f3..d02dda5350b7 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import StrPath -from typing import IO, Any, Container, Iterable, Sequence, TypeVar, overload -from typing_extensions import Literal +from collections.abc import Container, Iterable, Sequence +from typing import Any, Protocol, TypeVar, overload +from typing_extensions import Final, Literal if sys.version_info >= (3, 11): __all__ = [ @@ -67,9 +68,14 @@ else: "ngettext", ] +class _TranslationsReader(Protocol): + def read(self) -> bytes: ... + # optional: + # name: str + class NullTranslations: - def __init__(self, fp: IO[str] | None = ...) -> None: ... - def _parse(self, fp: IO[str]) -> None: ... + def __init__(self, fp: _TranslationsReader | None = ...) -> None: ... + def _parse(self, fp: _TranslationsReader) -> None: ... def add_fallback(self, fallback: NullTranslations) -> None: ... def gettext(self, message: str) -> str: ... def lgettext(self, message: str) -> str: ... @@ -79,18 +85,18 @@ class NullTranslations: def pgettext(self, context: str, message: str) -> str: ... def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... - def info(self) -> Any: ... - def charset(self) -> Any: ... + def info(self) -> dict[str, str]: ... + def charset(self) -> str | None: ... if sys.version_info < (3, 11): - def output_charset(self) -> Any: ... + def output_charset(self) -> str | None: ... def set_output_charset(self, charset: str) -> None: ... def install(self, names: Container[str] | None = ...) -> None: ... class GNUTranslations(NullTranslations): - LE_MAGIC: int - BE_MAGIC: int - CONTEXT: str + LE_MAGIC: Final[int] + BE_MAGIC: Final[int] + CONTEXT: Final[str] VERSIONS: Sequence[int] @overload # ignores incompatible overloads diff --git a/mypy/typeshed/stdlib/glob.pyi b/mypy/typeshed/stdlib/glob.pyi index ced0ceceb205..c63563d19f58 100644 --- a/mypy/typeshed/stdlib/glob.pyi +++ b/mypy/typeshed/stdlib/glob.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import StrOrBytesPath -from typing import AnyStr, Iterator +from collections.abc import Iterator +from typing import AnyStr __all__ = ["escape", "glob", "iglob"] diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi index cae2a07e95c6..2fca402bf906 100644 --- a/mypy/typeshed/stdlib/graphlib.pyi +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import SupportsItems -from typing import Any, Generic, Iterable, TypeVar +from collections.abc import Iterable +from typing import Any, Generic, TypeVar __all__ = ["TopologicalSorter", "CycleError"] diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index 7347949ae865..abf12925aea2 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -4,16 +4,16 @@ import zlib from _typeshed import ReadableBuffer, StrOrBytesPath from io import FileIO from typing import Any, Protocol, TextIO, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 8): __all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] else: __all__ = ["GzipFile", "open", "compress", "decompress"] -_ReadBinaryMode = Literal["r", "rb"] -_WriteBinaryMode = Literal["a", "ab", "w", "wb", "x", "xb"] -_OpenTextMode = Literal["rt", "at", "wt", "xt"] +_ReadBinaryMode: TypeAlias = Literal["r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["a", "ab", "w", "wb", "x", "xb"] +_OpenTextMode: TypeAlias = Literal["rt", "at", "wt", "xt"] READ: Literal[1] WRITE: Literal[2] diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 4332153d281c..2a417364b171 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -1,28 +1,52 @@ import sys from _typeshed import ReadableBuffer, Self -from typing import AbstractSet +from collections.abc import Callable, Set as AbstractSet +from typing import Protocol from typing_extensions import final -__all__ = ( - "md5", - "sha1", - "sha224", - "sha256", - "sha384", - "sha512", - "blake2b", - "blake2s", - "sha3_224", - "sha3_256", - "sha3_384", - "sha3_512", - "shake_128", - "shake_256", - "new", - "algorithms_guaranteed", - "algorithms_available", - "pbkdf2_hmac", -) +if sys.version_info >= (3, 11): + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "pbkdf2_hmac", + "file_digest", + ) +else: + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "pbkdf2_hmac", + ) class _Hash: @property @@ -143,3 +167,15 @@ class _BlakeHash(_Hash): blake2b = _BlakeHash blake2s = _BlakeHash + +if sys.version_info >= (3, 11): + class _BytesIOLike(Protocol): + def getbuffer(self) -> ReadableBuffer: ... + + class _FileDigestFileObj(Protocol): + def readinto(self, __buf: bytearray) -> int: ... + def readable(self) -> bool: ... + + def file_digest( + __fileobj: _BytesIOLike | _FileDigestFileObj, __digest: str | Callable[[], _Hash], *, _bufsize: int = ... + ) -> _Hash: ... diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index a7a787d44e62..f07afc7af706 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -1,6 +1,7 @@ from _heapq import * from _typeshed import SupportsRichComparison -from typing import Any, Callable, Iterable, TypeVar +from collections.abc import Callable, Iterable +from typing import Any, TypeVar __all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"] diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 6d355147f51e..858e46a71b68 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -1,11 +1,13 @@ import sys from _typeshed import ReadableBuffer +from collections.abc import Callable from types import ModuleType -from typing import Any, AnyStr, Callable, overload +from typing import Any, AnyStr, overload +from typing_extensions import TypeAlias # TODO more precise type for object of hashlib -_Hash = Any -_DigestMod = str | Callable[[], _Hash] | ModuleType +_Hash: TypeAlias = Any +_DigestMod: TypeAlias = str | Callable[[], _Hash] | ModuleType trans_5C: bytes trans_36: bytes diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 801a195c9fb3..235b6d6b4951 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -4,8 +4,10 @@ import ssl import sys import types from _typeshed import Self, WriteableBuffer +from collections.abc import Callable, Iterable, Iterator, Mapping from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, overload +from typing import IO, Any, BinaryIO, Protocol, TypeVar, overload +from typing_extensions import TypeAlias __all__ = [ "HTTPResponse", @@ -29,7 +31,7 @@ __all__ = [ "HTTPSConnection", ] -_DataType = bytes | IO[Any] | Iterable[bytes] | str +_DataType: TypeAlias = bytes | IO[Any] | Iterable[bytes] | str _T = TypeVar("_T") HTTP_PORT: int diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 4fb1c38c6ab8..83da7faaf0fc 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import StrPath +from collections.abc import Iterable, Iterator, Sequence from http.client import HTTPResponse -from typing import ClassVar, Iterable, Iterator, Pattern, Sequence, TypeVar, overload +from typing import ClassVar, Pattern, TypeVar, overload from urllib.request import Request __all__ = [ diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index 2cc05961a303..e5aa2c1609db 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -1,12 +1,14 @@ import sys -from typing import Any, Generic, Iterable, Mapping, TypeVar, overload +from collections.abc import Iterable, Mapping +from typing import Any, Generic, TypeVar, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] -_DataType = str | Mapping[str, str | Morsel[Any]] +_DataType: TypeAlias = str | Mapping[str, str | Morsel[Any]] _T = TypeVar("_T") @overload diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index 53159b65ec14..ad314cec1541 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -3,7 +3,8 @@ import io import socketserver import sys from _typeshed import StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, BinaryIO, ClassVar, Mapping, Sequence +from collections.abc import Mapping, Sequence +from typing import Any, AnyStr, BinaryIO, ClassVar if sys.version_info >= (3, 7): __all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler"] diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index ab6490cea570..eef1c1957769 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -2,21 +2,21 @@ import subprocess import sys import time from _typeshed import Self +from builtins import list as _list # conflicts with a method named "list" +from collections.abc import Callable from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, Pattern -from typing_extensions import Literal +from typing import IO, Any, Pattern +from typing_extensions import Literal, TypeAlias __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] # TODO: Commands should use their actual return types, not this type alias. # E.g. Tuple[Literal["OK"], List[bytes]] -_CommandResults = tuple[str, list[Any]] +_CommandResults: TypeAlias = tuple[str, list[Any]] -_AnyResponseData = list[None] | list[bytes | tuple[bytes, bytes]] - -_list = list # conflicts with a method named "list" +_AnyResponseData: TypeAlias = list[None] | list[bytes | tuple[bytes, bytes]] class IMAP4: error: type[Exception] diff --git a/mypy/typeshed/stdlib/imghdr.pyi b/mypy/typeshed/stdlib/imghdr.pyi index af046e899326..5f439779a69c 100644 --- a/mypy/typeshed/stdlib/imghdr.pyi +++ b/mypy/typeshed/stdlib/imghdr.pyi @@ -1,5 +1,6 @@ from _typeshed import StrPath -from typing import Any, BinaryIO, Callable, Protocol, overload +from collections.abc import Callable +from typing import Any, BinaryIO, Protocol, overload __all__ = ["what"] diff --git a/mypy/typeshed/stdlib/importlib/__init__.pyi b/mypy/typeshed/stdlib/importlib/__init__.pyi index 0e99786775b0..42401a00bdeb 100644 --- a/mypy/typeshed/stdlib/importlib/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/__init__.pyi @@ -1,6 +1,6 @@ +from collections.abc import Mapping, Sequence from importlib.abc import Loader from types import ModuleType -from typing import Mapping, Sequence __all__ = ["__import__", "import_module", "invalidate_caches", "reload"] diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 877f8ff1a65c..63fd02f7b3d5 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -10,12 +10,13 @@ from _typeshed import ( StrPath, ) from abc import ABCMeta, abstractmethod +from collections.abc import Iterator, Mapping, Sequence from importlib.machinery import ModuleSpec from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, overload, runtime_checkable -from typing_extensions import Literal +from typing import IO, Any, BinaryIO, NoReturn, Protocol, overload, runtime_checkable +from typing_extensions import Literal, TypeAlias -_Path = bytes | str +_Path: TypeAlias = bytes | str class Finder(metaclass=ABCMeta): ... diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index f15ac48af5c5..09abdc6f34fd 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -1,7 +1,8 @@ import importlib.abc import sys import types -from typing import Any, Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Sequence +from typing import Any if sys.version_info >= (3, 8): from importlib.metadata import DistributionFinder, PathDistribution diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index 52c5547a6128..1f32f0770b37 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -2,12 +2,12 @@ import abc import pathlib import sys from _typeshed import Self, StrPath -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from email.message import Message from importlib.abc import MetaPathFinder from os import PathLike from pathlib import Path -from typing import Any, ClassVar, Iterable, NamedTuple, Pattern, overload +from typing import Any, ClassVar, NamedTuple, Pattern, overload if sys.version_info >= (3, 10): __all__ = [ diff --git a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi index a5e5733396d7..a1101df0d5ce 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -1,4 +1,5 @@ -from typing import Any, Iterator, Protocol, TypeVar +from collections.abc import Iterator +from typing import Any, Protocol, TypeVar _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index e6e3035e5dac..04d7e8dcc967 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -1,9 +1,11 @@ import os import sys +from collections.abc import Iterator from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType -from typing import Any, BinaryIO, Iterator, TextIO +from typing import Any, BinaryIO, TextIO +from typing_extensions import TypeAlias if sys.version_info >= (3, 10): __all__ = [ @@ -37,8 +39,8 @@ elif sys.version_info >= (3, 9): else: __all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] -Package = str | ModuleType -Resource = str | os.PathLike[Any] +Package: TypeAlias = str | ModuleType +Resource: TypeAlias = str | os.PathLike[Any] def open_binary(package: Package, resource: Resource) -> BinaryIO: ... def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index c759d7def5be..2546c2c7882f 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -3,7 +3,8 @@ import importlib.machinery import sys import types from _typeshed import StrOrBytesPath -from typing import Any, Callable +from collections.abc import Callable +from typing import Any from typing_extensions import ParamSpec _P = ParamSpec("_P") diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index f87cd0e55acb..7ca9c9bb3fc4 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -3,7 +3,7 @@ import sys import types from _typeshed import Self from collections import OrderedDict -from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence, Set as AbstractSet +from collections.abc import Awaitable, Callable, Coroutine, Generator, Mapping, Sequence, Set as AbstractSet from types import ( AsyncGeneratorType, BuiltinFunctionType, @@ -19,6 +19,7 @@ from types import ( ModuleType, TracebackType, ) +from typing_extensions import TypeAlias if sys.version_info >= (3, 7): from types import ( @@ -29,7 +30,7 @@ if sys.version_info >= (3, 7): MethodWrapperType, ) -from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar, Union +from typing import Any, ClassVar, NamedTuple, Protocol, TypeVar, Union from typing_extensions import Literal, ParamSpec, TypeGuard if sys.version_info >= (3, 11): @@ -165,8 +166,8 @@ TPFLAGS_IS_ABSTRACT: Literal[1048576] modulesbyfile: dict[str, Any] -_GetMembersPredicate = Callable[[Any], bool] -_GetMembersReturn = list[tuple[str, Any]] +_GetMembersPredicate: TypeAlias = Callable[[Any], bool] +_GetMembersReturn: TypeAlias = list[tuple[str, Any]] def getmembers(object: object, predicate: _GetMembersPredicate | None = ...) -> _GetMembersReturn: ... @@ -242,7 +243,9 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType: TypeAlias = Union[ + ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any] +] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: str | None = ...) -> str: ... @@ -511,7 +514,7 @@ def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: . # Create private type alias to avoid conflict with symbol of same # name created in Attribute class. -_Object = object +_Object: TypeAlias = object class Attribute(NamedTuple): name: str diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index ef4789251cc3..327fd0d94a4d 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -2,9 +2,10 @@ import builtins import codecs import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer +from collections.abc import Callable, Iterable, Iterator from os import _Opener from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, TextIO +from typing import IO, Any, BinaryIO, TextIO from typing_extensions import Literal if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index d777cef74597..1fdc6c57d8a8 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Self -from typing import Any, Container, Generic, Iterable, Iterator, SupportsInt, TypeVar, overload -from typing_extensions import Literal +from collections.abc import Container, Iterable, Iterator +from typing import Any, Generic, SupportsInt, TypeVar, overload +from typing_extensions import Literal, TypeAlias # Undocumented length constants IPV4LENGTH: Literal[32] @@ -10,8 +11,8 @@ IPV6LENGTH: Literal[128] _A = TypeVar("_A", IPv4Address, IPv6Address) _N = TypeVar("_N", IPv4Network, IPv6Network) -_RawIPAddress = int | str | bytes | IPv4Address | IPv6Address -_RawNetworkPart = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface +_RawIPAddress: TypeAlias = int | str | bytes | IPv4Address | IPv6Address +_RawNetworkPart: TypeAlias = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface def ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: ... def ip_network(address: _RawIPAddress | _RawNetworkPart, strict: bool = ...) -> IPv4Network | IPv6Network: ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index bec03b1876ac..43a0e8038d69 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,7 +1,8 @@ import sys -from _typeshed import Self, _T_co -from typing import Any, Callable, Generic, Iterable, Iterator, SupportsComplex, SupportsFloat, SupportsInt, TypeVar, overload -from typing_extensions import Literal, SupportsIndex +from _typeshed import Self +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Generic, SupportsComplex, SupportsFloat, SupportsInt, TypeVar, overload +from typing_extensions import Literal, SupportsIndex, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -9,9 +10,17 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _S = TypeVar("_S") _N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) -_Step = int | float | SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex +_T_co = TypeVar("_T_co", covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") + +_Step: TypeAlias = int | float | SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex -Predicate = Callable[[_T], object] +_Predicate: TypeAlias = Callable[[_T], object] # Technically count can take anything that implements a number protocol and has an add method # but we can't enforce the add method @@ -67,18 +76,15 @@ class compress(Iterator[_T], Generic[_T]): def __next__(self) -> _T: ... class dropwhile(Iterator[_T], Generic[_T]): - def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... + def __init__(self, __predicate: _Predicate[_T], __iterable: Iterable[_T]) -> None: ... def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... class filterfalse(Iterator[_T], Generic[_T]): - def __init__(self, __predicate: Predicate[_T] | None, __iterable: Iterable[_T]) -> None: ... + def __init__(self, __predicate: _Predicate[_T] | None, __iterable: Iterable[_T]) -> None: ... def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... -_T1 = TypeVar("_T1") -_T2 = TypeVar("_T2") - class groupby(Iterator[tuple[_T, Iterator[_S]]], Generic[_T, _S]): @overload def __new__(cls, iterable: Iterable[_T1], key: None = ...) -> groupby[_T1, _T1]: ... @@ -101,21 +107,91 @@ class starmap(Iterator[_T], Generic[_T]): def __next__(self) -> _T: ... class takewhile(Iterator[_T], Generic[_T]): - def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... + def __init__(self, __predicate: _Predicate[_T], __iterable: Iterable[_T]) -> None: ... def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... def tee(__iterable: Iterable[_T], __n: int = ...) -> tuple[Iterator[_T], ...]: ... -class zip_longest(Iterator[Any]): - def __init__(self, *p: Iterable[Any], fillvalue: Any = ...) -> None: ... +class zip_longest(Iterator[_T_co], Generic[_T_co]): + # one iterable (fillvalue doesn't matter) + @overload + def __new__(cls, __iter1: Iterable[_T1], *, fillvalue: object = ...) -> zip_longest[tuple[_T1]]: ... + # two iterables + @overload + # In the overloads without fillvalue, all of the tuple members could theoretically be None, + # but we return Any instead to avoid false positives for code where we know one of the iterables + # is longer. + def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip_longest[tuple[_T1 | Any, _T2 | Any]]: ... + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T]]: ... + # three iterables + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] + ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any]]: ... + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T]]: ... + # four iterables + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any, _T4 | Any]]: ... + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T]]: ... + # five iterables + @overload + def __new__( + cls, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any, _T4 | Any, _T5 | Any]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + *, + fillvalue: _T, + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T, _T5 | _T]]: ... + # six or more iterables + @overload + def __new__( + cls, + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + __iter4: Iterable[_T], + __iter5: Iterable[_T], + __iter6: Iterable[_T], + *iterables: Iterable[_T], + ) -> zip_longest[tuple[_T | Any, ...]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[_T], + __iter2: Iterable[_T], + __iter3: Iterable[_T], + __iter4: Iterable[_T], + __iter5: Iterable[_T], + __iter6: Iterable[_T], + *iterables: Iterable[_T], + fillvalue: _T, + ) -> zip_longest[tuple[_T, ...]]: ... def __iter__(self: Self) -> Self: ... - def __next__(self) -> Any: ... - -_T3 = TypeVar("_T3") -_T4 = TypeVar("_T4") -_T5 = TypeVar("_T5") -_T6 = TypeVar("_T6") + def __next__(self) -> _T_co: ... class product(Iterator[_T_co], Generic[_T_co]): @overload diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 8e1a36756398..2fd87622e1fe 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -1,5 +1,6 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable +from collections.abc import Callable +from typing import IO, Any from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder from .encoder import JSONEncoder as JSONEncoder diff --git a/mypy/typeshed/stdlib/json/decoder.pyi b/mypy/typeshed/stdlib/json/decoder.pyi index 866836758545..2060cf17dd05 100644 --- a/mypy/typeshed/stdlib/json/decoder.pyi +++ b/mypy/typeshed/stdlib/json/decoder.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable +from collections.abc import Callable +from typing import Any __all__ = ["JSONDecoder", "JSONDecodeError"] diff --git a/mypy/typeshed/stdlib/json/encoder.pyi b/mypy/typeshed/stdlib/json/encoder.pyi index 6dd74896e5a0..ecd1fa78ad99 100644 --- a/mypy/typeshed/stdlib/json/encoder.pyi +++ b/mypy/typeshed/stdlib/json/encoder.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable, Iterator, Pattern +from collections.abc import Callable, Iterator +from typing import Any, Pattern ESCAPE: Pattern[str] ESCAPE_ASCII: Pattern[str] diff --git a/mypy/typeshed/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi index e9a9877d57da..c17c58012fd1 100644 --- a/mypy/typeshed/stdlib/keyword.pyi +++ b/mypy/typeshed/stdlib/keyword.pyi @@ -1,5 +1,5 @@ import sys -from typing import Sequence +from collections.abc import Sequence if sys.version_info >= (3, 9): __all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi index 4ecba031942c..61ec90b4d582 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi @@ -1,8 +1,9 @@ from _typeshed import StrPath +from collections.abc import Iterable from lib2to3.pgen2.grammar import Grammar from lib2to3.pytree import _NL, _Convert from logging import Logger -from typing import IO, Any, Iterable +from typing import IO, Any __all__ = ["Driver", "load_grammar"] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index b5836e1b90c5..4d298ec6972c 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,8 +1,9 @@ from _typeshed import Self, StrPath +from typing_extensions import TypeAlias -_Label = tuple[int, str | None] -_DFA = list[list[tuple[int, int]]] -_DFAS = tuple[_DFA, dict[int, int]] +_Label: TypeAlias = tuple[int, str | None] +_DFA: TypeAlias = list[list[tuple[int, int]]] +_DFAS: TypeAlias = tuple[_DFA, dict[int, int]] class Grammar: symbol2number: dict[str, int] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi index e776ed1e5a61..14d6004d3423 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -1,8 +1,10 @@ +from collections.abc import Sequence from lib2to3.pgen2.grammar import _DFAS, Grammar from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, Sequence +from typing import Any +from typing_extensions import TypeAlias -_Context = Sequence[Any] +_Context: TypeAlias = Sequence[Any] class ParseError(Exception): msg: str diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi index 2628e1223fb4..e3ea07432d70 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi @@ -1,7 +1,8 @@ from _typeshed import StrPath +from collections.abc import Iterable, Iterator from lib2to3.pgen2 import grammar from lib2to3.pgen2.tokenize import _TokenInfo -from typing import IO, Any, Iterable, Iterator, NoReturn +from typing import IO, Any, NoReturn class PgenGrammar(grammar.Grammar): ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index c1b5a91df9e6..a998ad5fe49e 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,6 +1,7 @@ import sys +from collections.abc import Callable, Iterable, Iterator from lib2to3.pgen2.token import * -from typing import Callable, Iterable, Iterator +from typing_extensions import TypeAlias if sys.version_info >= (3, 8): __all__ = [ @@ -146,9 +147,9 @@ else: "untokenize", ] -_Coord = tuple[int, int] -_TokenEater = Callable[[int, str, _Coord, _Coord, str], None] -_TokenInfo = tuple[int, str, _Coord, _Coord, str] +_Coord: TypeAlias = tuple[int, int] +_TokenEater: TypeAlias = Callable[[int, str, _Coord, _Coord, str], None] +_TokenInfo: TypeAlias = tuple[int, str, _Coord, _Coord, str] class TokenError(Exception): ... class StopTokenizing(Exception): ... diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index 68e5d8ba1323..fa0cb9e34f75 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,12 +1,14 @@ from _typeshed import Self +from collections.abc import Callable, Iterator from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator +from typing import Any +from typing_extensions import TypeAlias -_NL = Node | Leaf -_Context = tuple[str, int, int] -_Results = dict[str, _NL] -_RawNode = tuple[int, str, _Context, list[_NL] | None] -_Convert = Callable[[Grammar, _RawNode], Any] +_NL: TypeAlias = Node | Leaf +_Context: TypeAlias = tuple[str, int, int] +_Results: TypeAlias = dict[str, _NL] +_RawNode: TypeAlias = tuple[int, str, _Context, list[_NL] | None] +_Convert: TypeAlias = Callable[[Grammar, _RawNode], Any] HUGE: int diff --git a/mypy/typeshed/stdlib/lib2to3/refactor.pyi b/mypy/typeshed/stdlib/lib2to3/refactor.pyi index 6687092d862c..3aaea0e519d9 100644 --- a/mypy/typeshed/stdlib/lib2to3/refactor.pyi +++ b/mypy/typeshed/stdlib/lib2to3/refactor.pyi @@ -1,11 +1,12 @@ from collections.abc import Container, Generator, Iterable, Mapping from logging import Logger from typing import Any, ClassVar, NoReturn +from typing_extensions import TypeAlias from .pgen2.grammar import Grammar -_Driver = Any # really lib2to3.driver.Driver -_BottomMatcher = Any # really lib2to3.btm_matcher.BottomMatcher +_Driver: TypeAlias = Any # really lib2to3.driver.Driver +_BottomMatcher: TypeAlias = Any # really lib2to3.btm_matcher.BottomMatcher def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = ...) -> list[str]: ... def get_fixers_from_package(pkg_name: str) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index d72d678b5e18..df54fd80aea7 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -1,13 +1,14 @@ import sys from typing import Any, Protocol +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): __all__ = ["getline", "clearcache", "checkcache", "lazycache"] else: __all__ = ["getline", "clearcache", "checkcache"] -_ModuleGlobals = dict[str, Any] -_ModuleMetadata = tuple[int, float | None, list[str], str] +_ModuleGlobals: TypeAlias = dict[str, Any] +_ModuleMetadata: TypeAlias = tuple[int, float | None, list[str], str] class _SourceLoader(Protocol): def __call__(self) -> str | None: ... diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index e5227beca149..959054e847a8 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -1,5 +1,6 @@ import sys from _typeshed import StrPath +from collections.abc import Callable, Iterable, Mapping __all__ = [ "getlocale", @@ -32,7 +33,7 @@ __all__ = [ # as a type annotation or type alias. from builtins import str as _str from decimal import Decimal -from typing import Any, Callable, Iterable, Mapping +from typing import Any CODESET: int D_T_FMT: int diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 8de4d0d88260..edb15061a588 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -7,7 +7,7 @@ from string import Template from time import struct_time from types import FrameType, TracebackType from typing import Any, ClassVar, Generic, Pattern, TextIO, TypeVar, Union, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = [ "BASIC_FORMAT", @@ -54,12 +54,12 @@ __all__ = [ "raiseExceptions", ] -_SysExcInfoType = Union[tuple[type[BaseException], BaseException, TracebackType | None], tuple[None, None, None]] -_ExcInfoType = None | bool | _SysExcInfoType | BaseException -_ArgsType = tuple[object, ...] | Mapping[str, object] -_FilterType = Filter | Callable[[LogRecord], int] -_Level = int | str -_FormatStyle = Literal["%", "{", "$"] +_SysExcInfoType: TypeAlias = Union[tuple[type[BaseException], BaseException, TracebackType | None], tuple[None, None, None]] +_ExcInfoType: TypeAlias = None | bool | _SysExcInfoType | BaseException +_ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object] +_FilterType: TypeAlias = Filter | Callable[[LogRecord], int] +_Level: TypeAlias = int | str +_FormatStyle: TypeAlias = Literal["%", "{", "$"] raiseExceptions: bool logThreads: bool diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index 8ee9e7b339b5..5993ba97df4b 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import StrOrBytesPath, StrPath -from collections.abc import Callable +from collections.abc import Callable, Sequence from configparser import RawConfigParser from threading import Thread -from typing import IO, Any, Pattern, Sequence +from typing import IO, Any, Pattern +from typing_extensions import TypeAlias from . import _Level @@ -13,9 +14,9 @@ else: from typing_extensions import Literal, TypedDict if sys.version_info >= (3, 7): - _Path = StrOrBytesPath + _Path: TypeAlias = StrOrBytesPath else: - _Path = StrPath + _Path: TypeAlias = StrPath DEFAULT_LOGGING_CONFIG_PORT: int RESET_ERROR: int # undocumented diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index 45bf24b3ef6d..d4c7977b8d0a 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,7 +1,8 @@ import io from _typeshed import ReadableBuffer, Self, StrOrBytesPath -from typing import IO, Any, Mapping, Sequence, TextIO, overload -from typing_extensions import Literal, final +from collections.abc import Mapping, Sequence +from typing import IO, Any, TextIO, overload +from typing_extensions import Literal, TypeAlias, final __all__ = [ "CHECK_NONE", @@ -42,12 +43,12 @@ __all__ = [ "is_check_supported", ] -_OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] -_OpenTextWritingMode = Literal["wt", "xt", "at"] +_OpenBinaryWritingMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_OpenTextWritingMode: TypeAlias = Literal["wt", "xt", "at"] -_PathOrFile = StrOrBytesPath | IO[bytes] +_PathOrFile: TypeAlias = StrOrBytesPath | IO[bytes] -_FilterChain = Sequence[Mapping[str, Any]] +_FilterChain: TypeAlias = Sequence[Mapping[str, Any]] FORMAT_AUTO: Literal[0] FORMAT_XZ: Literal[1] diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 143891d3240b..64183cd0b3a4 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -2,9 +2,10 @@ import email.message import sys from _typeshed import Self, StrOrBytesPath from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, overload -from typing_extensions import Literal +from typing import IO, Any, AnyStr, Generic, Protocol, TypeVar, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -31,7 +32,7 @@ __all__ = [ _T = TypeVar("_T") _MessageT = TypeVar("_MessageT", bound=Message) -_MessageData = email.message.Message | bytes | str | IO[str] | IO[bytes] +_MessageData: TypeAlias = email.message.Message | bytes | str | IO[str] | IO[bytes] class _HasIteritems(Protocol): def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... diff --git a/mypy/typeshed/stdlib/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi index 232ab99c314d..e1637ad6e7be 100644 --- a/mypy/typeshed/stdlib/mailcap.pyi +++ b/mypy/typeshed/stdlib/mailcap.pyi @@ -1,6 +1,7 @@ -from typing import Mapping, Sequence +from collections.abc import Mapping, Sequence +from typing_extensions import TypeAlias -_Cap = dict[str, str | int] +_Cap: TypeAlias = dict[str, str | int] __all__ = ["getcaps", "findmatch"] diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index e4ab311990be..ada510d629ed 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -1,12 +1,13 @@ import sys from _typeshed import SupportsTrunc -from typing import Iterable, SupportsFloat, overload -from typing_extensions import SupportsIndex +from collections.abc import Iterable +from typing import SupportsFloat, overload +from typing_extensions import SupportsIndex, TypeAlias if sys.version_info >= (3, 8): - _SupportsFloatOrIndex = SupportsFloat | SupportsIndex + _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex else: - _SupportsFloatOrIndex = SupportsFloat + _SupportsFloatOrIndex: TypeAlias = SupportsFloat e: float pi: float diff --git a/mypy/typeshed/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi index e51b7cdf37bd..c2b6ff20281a 100644 --- a/mypy/typeshed/stdlib/mimetypes.pyi +++ b/mypy/typeshed/stdlib/mimetypes.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import StrPath -from typing import IO, Sequence +from collections.abc import Sequence +from typing import IO __all__ = [ "knownfiles", diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 744888172479..96bb01a271fc 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import ReadableBuffer, Self -from typing import Iterable, Iterator, NoReturn, Sized, overload +from collections.abc import Iterable, Iterator, Sized +from typing import NoReturn, overload ACCESS_DEFAULT: int ACCESS_READ: int diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index 9efe032cfd29..cd01e0e1381f 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -1,6 +1,7 @@ import sys +from collections.abc import Container, Iterable, Iterator, Sequence from types import CodeType -from typing import IO, Any, Container, Iterable, Iterator, Sequence +from typing import IO, Any LOAD_CONST: int # undocumented IMPORT_NAME: int # undocumented diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index c512489be34d..968efbec7a6c 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -1,6 +1,7 @@ import sys +from collections.abc import Container, Iterable, Sequence from types import ModuleType -from typing import Any, Container, Iterable, Sequence +from typing import Any from typing_extensions import Literal if sys.platform == "win32": diff --git a/mypy/typeshed/stdlib/msilib/sequence.pyi b/mypy/typeshed/stdlib/msilib/sequence.pyi index 30346aba3367..9cc1e0eaec01 100644 --- a/mypy/typeshed/stdlib/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/msilib/sequence.pyi @@ -1,8 +1,9 @@ import sys +from typing_extensions import TypeAlias if sys.platform == "win32": - _SequenceType = list[tuple[str, str | None, int]] + _SequenceType: TypeAlias = list[tuple[str, str | None, int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 3a8a382b8a27..87ceda10573d 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -20,8 +20,8 @@ from multiprocessing.process import active_children as active_children, current_ # multiprocessing.queues or the aliases defined below. See #4266 for discussion. from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support -from typing import Any, overload -from typing_extensions import Literal +from typing import Any, TypeVar, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 8): from multiprocessing.process import parent_process as parent_process @@ -118,23 +118,24 @@ else: # from multiprocessing import _LockType # lock: _LockType = Lock() -_QueueType = Queue -_SimpleQueueType = SimpleQueue -_JoinableQueueType = JoinableQueue -_BarrierType = synchronize.Barrier -_BoundedSemaphoreType = synchronize.BoundedSemaphore -_ConditionType = synchronize.Condition -_EventType = synchronize.Event -_LockType = synchronize.Lock -_RLockType = synchronize.RLock -_SemaphoreType = synchronize.Semaphore +_T = TypeVar("_T") +_QueueType: TypeAlias = Queue[_T] +_SimpleQueueType: TypeAlias = SimpleQueue[_T] +_JoinableQueueType: TypeAlias = JoinableQueue[_T] +_BarrierType: TypeAlias = synchronize.Barrier +_BoundedSemaphoreType: TypeAlias = synchronize.BoundedSemaphore +_ConditionType: TypeAlias = synchronize.Condition +_EventType: TypeAlias = synchronize.Event +_LockType: TypeAlias = synchronize.Lock +_RLockType: TypeAlias = synchronize.RLock +_SemaphoreType: TypeAlias = synchronize.Semaphore # N.B. The functions below are generated at runtime by partially applying # multiprocessing.context.BaseContext's methods, so the two signatures should # be identical (modulo self). # Synchronization primitives -_LockLike = synchronize.Lock | synchronize.RLock +_LockLike: TypeAlias = synchronize.Lock | synchronize.RLock RawValue = context._default_context.RawValue RawArray = context._default_context.RawArray Value = context._default_context.Value diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index 5db6fa4cda7e..7b227a697abe 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -2,13 +2,14 @@ import socket import sys import types from _typeshed import Self -from typing import Any, Iterable, Union -from typing_extensions import SupportsIndex +from collections.abc import Iterable +from typing import Any, Union +from typing_extensions import SupportsIndex, TypeAlias __all__ = ["Client", "Listener", "Pipe", "wait"] # https://docs.python.org/3/library/multiprocessing.html#address-formats -_Address = Union[str, tuple[str, int]] +_Address: TypeAlias = Union[str, tuple[str, int]] class _ConnectionBase: def __init__(self, handle: SupportsIndex, readable: bool = ..., writable: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index 315918a04b98..d618d1028112 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -9,14 +9,14 @@ from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase from typing import Any, ClassVar, TypeVar, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 8): __all__ = () else: __all__: list[str] = [] -_LockLike = synchronize.Lock | synchronize.RLock +_LockLike: TypeAlias = synchronize.Lock | synchronize.RLock _CT = TypeVar("_CT", bound=_CData) class ProcessError(Exception): ... diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi index 48f42999866a..bbddfd16ded7 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi @@ -1,8 +1,9 @@ import array import threading import weakref +from collections.abc import Callable, Iterable, Mapping, Sequence from queue import Queue as Queue -from typing import Any, Callable, Iterable, Mapping, Sequence +from typing import Any from typing_extensions import Literal from .connection import Pipe as Pipe diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi index c61617cd91d4..fd909d0d32e1 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi @@ -2,12 +2,13 @@ from _typeshed import Self from queue import Queue from types import TracebackType from typing import Any, Union +from typing_extensions import TypeAlias __all__ = ["Client", "Listener", "Pipe"] families: list[None] -_Address = Union[str, tuple[str, int]] +_Address: TypeAlias = Union[str, tuple[str, int]] class Connection: _in: Any diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index a0f76b636c4b..234660cc4f80 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -2,19 +2,20 @@ import queue import sys import threading from _typeshed import Self +from builtins import dict as _dict, list as _list # Conflicts with method names +from collections.abc import Callable, Iterable, Mapping, Sequence from types import TracebackType -from typing import Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar +from typing import Any, AnyStr, Generic, TypeVar +from typing_extensions import TypeAlias from .connection import Connection from .context import BaseContext if sys.version_info >= (3, 8): - from .shared_memory import _SLT, ShareableList, SharedMemory + from .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] - _SharedMemory = SharedMemory - _ShareableList = ShareableList else: __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token"] @@ -30,7 +31,7 @@ class Namespace: def __getattr__(self, __name: str) -> Any: ... def __setattr__(self, __name: str, __value: Any) -> None: ... -_Namespace = Namespace +_Namespace: TypeAlias = Namespace class Token: typeid: str | bytes | None @@ -100,10 +101,6 @@ class BaseManager: self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... -# Conflicts with method names -_dict = dict -_list = list - class SyncManager(BaseManager): def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... def Condition(self, lock: Any = ...) -> threading.Condition: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 5e38e0161834..c0d01e98dfae 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Self +from collections.abc import Callable, Iterable, Iterator, Mapping from types import TracebackType -from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, TypeVar +from typing import Any, Generic, TypeVar from typing_extensions import Literal if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index a4c4fd071c5f..76ccedaf478e 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import Self -from typing import Any, Generic, Iterable, TypeVar +from collections.abc import Iterable +from typing import Any, Generic, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/multiprocessing/spawn.pyi b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi index 4f981ea467c4..50570ff3717b 100644 --- a/mypy/typeshed/stdlib/multiprocessing/spawn.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/spawn.pyi @@ -1,5 +1,6 @@ +from collections.abc import Mapping, Sequence from types import ModuleType -from typing import Any, Mapping, Sequence +from typing import Any __all__ = [ "_main", diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index 0cfc815b2d82..e93d6c58b5cf 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -1,13 +1,15 @@ import sys import threading +from collections.abc import Callable from contextlib import AbstractContextManager from multiprocessing.context import BaseContext from types import TracebackType -from typing import Any, Callable +from typing import Any +from typing_extensions import TypeAlias __all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] -_LockLike = Lock | RLock +_LockLike: TypeAlias = Lock | RLock class Barrier(threading.Barrier): def __init__( diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index 45f6cfbeda7b..803c78073348 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,4 +1,5 @@ from _typeshed import StrOrBytesPath +from typing_extensions import TypeAlias __all__ = ["netrc", "NetrcParseError"] @@ -9,7 +10,7 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: StrOrBytesPath | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = tuple[str, str | None, str | None] +_NetrcTuple: TypeAlias = tuple[str, str | None, str | None] class netrc: hosts: dict[str, _NetrcTuple] diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index cc48cb83ae4c..aa5bcba5726c 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -3,8 +3,10 @@ import socket import ssl import sys from _typeshed import Self -from typing import IO, Any, Iterable, NamedTuple -from typing_extensions import Literal +from builtins import list as _list # conflicts with a method named "list" +from collections.abc import Iterable +from typing import IO, Any, NamedTuple +from typing_extensions import Literal, TypeAlias __all__ = [ "NNTP", @@ -18,7 +20,7 @@ __all__ = [ "NNTP_SSL", ] -_File = IO[bytes] | bytes | str | None +_File: TypeAlias = IO[bytes] | bytes | str | None class NNTPError(Exception): response: str @@ -45,8 +47,6 @@ class ArticleInfo(NamedTuple): def decode_header(header_str: str) -> str: ... -_list = list # conflicts with a method named "list" - class NNTP: encoding: str errors: str diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 7aedf583e556..1e7428f59a95 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,5 +1,6 @@ from abc import abstractmethod -from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, overload +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import IO, Any, AnyStr, overload __all__ = [ "Option", diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 2ef781bbe288..76c114591d32 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -14,28 +14,12 @@ from _typeshed import ( ) from abc import abstractmethod from builtins import OSError +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence from contextlib import AbstractContextManager from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper from subprocess import Popen -from typing import ( - IO, - Any, - AnyStr, - BinaryIO, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - MutableMapping, - NoReturn, - Protocol, - Sequence, - TypeVar, - overload, - runtime_checkable, -) -from typing_extensions import Final, Literal, final +from typing import IO, Any, AnyStr, BinaryIO, Generic, NoReturn, Protocol, TypeVar, overload, runtime_checkable +from typing_extensions import Final, Literal, TypeAlias, final from . import path as _path @@ -211,7 +195,7 @@ R_OK: int W_OK: int X_OK: int -_EnvironCodeFunc = Callable[[AnyStr], AnyStr] +_EnvironCodeFunc: TypeAlias = Callable[[AnyStr], AnyStr] class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): encodekey: _EnvironCodeFunc[AnyStr] @@ -383,7 +367,7 @@ def listdir(path: BytesPath) -> list[bytes]: ... @overload def listdir(path: int) -> list[str]: ... -_FdOrAnyPath = int | StrOrBytesPath +_FdOrAnyPath: TypeAlias = int | StrOrBytesPath @final class DirEntry(Generic[AnyStr]): @@ -404,9 +388,9 @@ class DirEntry(Generic[AnyStr]): def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 7): - _StatVfsTuple = tuple[int, int, int, int, int, int, int, int, int, int, int] + _StatVfsTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int, int] else: - _StatVfsTuple = tuple[int, int, int, int, int, int, int, int, int, int] + _StatVfsTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int] @final class statvfs_result(structseq[int], _StatVfsTuple): @@ -527,7 +511,7 @@ def putenv(__name: bytes | str, __value: bytes | str) -> None: ... if sys.platform != "win32" or sys.version_info >= (3, 9): def unsetenv(__name: bytes | str) -> None: ... -_Opener = Callable[[str, int], int] +_Opener: TypeAlias = Callable[[str, int], int] @overload def fdopen( @@ -787,7 +771,7 @@ def utime( follow_symlinks: bool = ..., ) -> None: ... -_OnError = Callable[[OSError], Any] +_OnError: TypeAlias = Callable[[OSError], Any] def walk( top: AnyStr | PathLike[AnyStr], topdown: bool = ..., onerror: _OnError | None = ..., followlinks: bool = ... @@ -845,7 +829,7 @@ def execlpe(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoRetur # Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference # in practice, and doing so would explode the number of combinations in this already long union. # All these combinations are necessary due to list being invariant. -_ExecVArgs = ( +_ExecVArgs: TypeAlias = ( tuple[StrOrBytesPath, ...] | list[bytes] | list[str] @@ -855,7 +839,7 @@ _ExecVArgs = ( | list[str | PathLike[Any]] | list[bytes | str | PathLike[Any]] ) -_ExecEnv = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] +_ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] def execv(__path: StrOrBytesPath, __argv: _ExecVArgs) -> NoReturn: ... def execve(path: _FdOrAnyPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... diff --git a/mypy/typeshed/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi index 95e770b57256..cce8594eac58 100644 --- a/mypy/typeshed/stdlib/parser.pyi +++ b/mypy/typeshed/stdlib/parser.pyi @@ -1,6 +1,7 @@ from _typeshed import StrOrBytesPath +from collections.abc import Sequence from types import CodeType -from typing import Any, Sequence +from typing import Any from typing_extensions import final def expr(source: str) -> STType: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index 45917ce59f8f..65aead6cb4de 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -8,10 +8,11 @@ from _typeshed import ( Self, StrPath, ) +from collections.abc import Generator, Sequence from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike, stat_result from types import TracebackType -from typing import IO, Any, BinaryIO, Generator, Sequence, overload +from typing import IO, Any, BinaryIO, overload from typing_extensions import Literal if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi index c1cba5e8d23b..e787b4a4c416 100644 --- a/mypy/typeshed/stdlib/pdb.pyi +++ b/mypy/typeshed/stdlib/pdb.pyi @@ -3,9 +3,10 @@ import sys from _typeshed import Self from bdb import Bdb from cmd import Cmd +from collections.abc import Callable, Iterable, Mapping, Sequence from inspect import _SourceObjectType from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, Sequence, TypeVar +from typing import IO, Any, ClassVar, TypeVar from typing_extensions import ParamSpec __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index 26ee94ca2682..d58cf8ed9d50 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,6 +1,8 @@ import sys -from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Protocol, Union -from typing_extensions import final +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable, Iterator, Mapping +from typing import Any, ClassVar, Protocol, SupportsBytes, Union +from typing_extensions import SupportsIndex, TypeAlias, final if sys.version_info >= (3, 8): __all__ = [ @@ -182,14 +184,12 @@ class _WritableFileobj(Protocol): def write(self, __b: bytes) -> Any: ... if sys.version_info >= (3, 8): - # TODO: holistic design for buffer interface (typing.Buffer?) @final class PickleBuffer: - # buffer must be a buffer-providing object - def __init__(self, buffer: Any) -> None: ... + def __init__(self, buffer: ReadableBuffer) -> None: ... def raw(self) -> memoryview: ... def release(self) -> None: ... - _BufferCallback = Callable[[PickleBuffer], Any] | None + _BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None def dump( obj: Any, file: _WritableFileobj, @@ -210,20 +210,25 @@ if sys.version_info >= (3, 8): buffers: Iterable[Any] | None = ..., ) -> Any: ... def loads( - __data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ..., buffers: Iterable[Any] | None = ... + __data: ReadableBuffer, + *, + fix_imports: bool = ..., + encoding: str = ..., + errors: str = ..., + buffers: Iterable[Any] | None = ..., ) -> Any: ... else: def dump(obj: Any, file: _WritableFileobj, protocol: int | None = ..., *, fix_imports: bool = ...) -> None: ... def dumps(obj: Any, protocol: int | None = ..., *, fix_imports: bool = ...) -> bytes: ... def load(file: _ReadableFileobj, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... - def loads(data: bytes, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... + def loads(data: ReadableBuffer, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ...) -> Any: ... class PickleError(Exception): ... class PicklingError(PickleError): ... class UnpicklingError(PickleError): ... -_reducedtype = Union[ +_reducedtype: TypeAlias = Union[ str, tuple[Callable[..., Any], tuple[Any, ...]], tuple[Callable[..., Any], tuple[Any, ...], Any], @@ -358,7 +363,7 @@ if sys.version_info >= (3, 8): READONLY_BUFFER: bytes def encode_long(x: int) -> bytes: ... # undocumented -def decode_long(data: bytes) -> int: ... # undocumented +def decode_long(data: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer) -> int: ... # undocumented # pure-Python implementations _Pickler = Pickler # undocumented diff --git a/mypy/typeshed/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi index 7b79ddcff347..c78848464237 100644 --- a/mypy/typeshed/stdlib/pickletools.pyi +++ b/mypy/typeshed/stdlib/pickletools.pyi @@ -1,8 +1,10 @@ -from typing import IO, Any, Callable, Iterator, MutableMapping +from collections.abc import Callable, Iterator, MutableMapping +from typing import IO, Any +from typing_extensions import TypeAlias __all__ = ["dis", "genops", "optimize"] -_Reader = Callable[[IO[bytes]], Any] +_Reader: TypeAlias = Callable[[IO[bytes]], Any] bytes_types: tuple[type[Any], ...] UP_TO_NEWLINE: int diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 7c27f6702a7e..5a93a9f86812 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import SupportsRead +from collections.abc import Callable, Iterable, Iterator from importlib.abc import Loader, MetaPathFinder, PathEntryFinder -from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple, TypeVar +from typing import IO, Any, NamedTuple, TypeVar __all__ = [ "get_importer", diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index 67d1611de828..de5fe1b75ca0 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import Self +from collections.abc import Mapping, MutableMapping from datetime import datetime from enum import Enum -from typing import IO, Any, Mapping, MutableMapping +from typing import IO, Any if sys.version_info >= (3, 9): __all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index 6b651e98e41f..487a7266694c 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -1,11 +1,12 @@ import socket import ssl +from builtins import list as _list # conflicts with a method named "list" from typing import Any, BinaryIO, NoReturn, Pattern, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["POP3", "error_proto", "POP3_SSL"] -_LongResp = tuple[bytes, list[bytes], int] +_LongResp: TypeAlias = tuple[bytes, list[bytes], int] class error_proto(Exception): ... @@ -16,8 +17,6 @@ LF: Literal[b"\n"] CRLF: Literal[b"\r\n"] HAVE_SSL: bool -_list = list # conflicts with a method named "list" - class POP3: encoding: str host: str diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index c72ba8a99bdd..4cec7c770ea3 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -1,5 +1,6 @@ import sys from _typeshed import BytesPath, StrOrBytesPath, StrPath +from collections.abc import Sequence from genericpath import ( commonprefix as commonprefix, exists as exists, @@ -14,7 +15,7 @@ from genericpath import ( samestat as samestat, ) from os import PathLike -from typing import AnyStr, Sequence, overload +from typing import AnyStr, overload __all__ = [ "normcase", diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index 982bcabad401..4b3f832d3224 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -1,6 +1,7 @@ from _typeshed import Self, StrOrBytesPath -from typing import Any, Callable, TypeVar -from typing_extensions import ParamSpec +from collections.abc import Callable +from typing import Any, TypeVar +from typing_extensions import ParamSpec, TypeAlias __all__ = ["run", "runctx", "Profile"] @@ -11,7 +12,7 @@ def runctx( _T = TypeVar("_T") _P = ParamSpec("_P") -_Label = tuple[str, int, str] +_Label: TypeAlias = tuple[str, int, str] class Profile: bias: int diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index a7b8bebe4066..7868512e5ab9 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import Self, StrOrBytesPath +from collections.abc import Iterable from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, overload -from typing_extensions import Literal +from typing import IO, Any, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): __all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] @@ -12,7 +13,7 @@ elif sys.version_info >= (3, 7): else: __all__ = ["Stats"] -_Selector = str | float | int +_Selector: TypeAlias = str | float | int if sys.version_info >= (3, 7): from enum import Enum @@ -45,7 +46,7 @@ if sys.version_info >= (3, 9): total_tt: float func_profiles: dict[str, FunctionProfile] -_SortArgDict = dict[str, tuple[tuple[tuple[int, int], ...], str]] +_SortArgDict: TypeAlias = dict[str, tuple[tuple[tuple[int, int], ...], str]] class Stats: sort_arg_dict_default: _SortArgDict diff --git a/mypy/typeshed/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi index 73c6ddfbd0c4..a6a2d8fabb69 100644 --- a/mypy/typeshed/stdlib/pty.pyi +++ b/mypy/typeshed/stdlib/pty.pyi @@ -1,10 +1,10 @@ import sys -from typing import Callable, Iterable -from typing_extensions import Literal +from collections.abc import Callable, Iterable +from typing_extensions import Literal, TypeAlias if sys.platform != "win32": __all__ = ["openpty", "fork", "spawn"] - _Reader = Callable[[int], bytes] + _Reader: TypeAlias = Callable[[int], bytes] STDIN_FILENO: Literal[0] STDOUT_FILENO: Literal[1] diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index b4fa66c60155..6e5d3e818f83 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,14 +1,13 @@ -from _typeshed import SupportsWrite +from _typeshed import OptExcInfo, SupportsWrite from abc import abstractmethod +from builtins import list as _list # "list" conflicts with method name +from collections.abc import Callable, Container, Mapping, MutableMapping from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, TypeVar +from typing import IO, Any, AnyStr, NoReturn, TypeVar __all__ = ["help"] -# the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = tuple[type[BaseException] | None, BaseException | None, TracebackType | None] - _T = TypeVar("_T") __author__: str @@ -36,7 +35,7 @@ class ErrorDuringImport(Exception): exc: type[BaseException] | None value: BaseException | None tb: TracebackType | None - def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... + def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ... def importfile(path: str) -> ModuleType: ... def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = ...) -> ModuleType: ... @@ -195,8 +194,6 @@ def doc(thing: str | object, title: str = ..., forceload: bool = ..., output: Su def writedoc(thing: str | object, forceload: bool = ...) -> None: ... def writedocs(dir: str, pkgpath: str = ..., done: Any | None = ...) -> None: ... -_list = list # "list" conflicts with method name - class Helper: keywords: dict[str, str | tuple[str, str]] symbols: dict[str, str] diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 24c93965b21f..2fe76a3d61b6 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -1,8 +1,9 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable -from typing_extensions import final +from collections.abc import Callable +from typing import Any +from typing_extensions import TypeAlias, final EXPAT_VERSION: str # undocumented version_info: tuple[int, int, int] # undocumented @@ -20,7 +21,7 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = tuple[int, int, str | None, tuple[Any, ...]] +_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] @final class XMLParserType: diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 612a54cb95b0..255436dc377d 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -89,7 +89,10 @@ class Random(_random.Random): cum_weights: Sequence[float | Fraction] | None = ..., k: int = ..., ) -> list[_T]: ... - def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def shuffle(self, x: MutableSequence[Any]) -> None: ... + else: + def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... if sys.version_info >= (3, 11): def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = ...) -> list[_T]: ... elif sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 57dab8eb820f..ff2a55fb4e61 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -1,8 +1,10 @@ import enum import sre_compile import sys +from collections.abc import Callable, Iterator from sre_constants import error as error -from typing import Any, AnyStr, Callable, Iterator, overload +from typing import Any, AnyStr, overload +from typing_extensions import TypeAlias # ----- re variables and constants ----- if sys.version_info >= (3, 7): @@ -147,7 +149,7 @@ T = RegexFlag.T TEMPLATE = RegexFlag.TEMPLATE if sys.version_info >= (3, 11): NOFLAG = RegexFlag.NOFLAG -_FlagsType = int | RegexFlag +_FlagsType: TypeAlias = int | RegexFlag if sys.version_info < (3, 7): # undocumented diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index df08a3cc25ff..ceca2e32f221 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,10 +1,11 @@ import sys from _typeshed import StrOrBytesPath -from typing import Callable, Sequence +from collections.abc import Callable, Sequence +from typing_extensions import TypeAlias if sys.platform != "win32": - _Completer = Callable[[str, int], str | None] - _CompDisp = Callable[[str, Sequence[str], int], None] + _Completer: TypeAlias = Callable[[str, int], str | None] + _CompDisp: TypeAlias = Callable[[str, Sequence[str], int], None] def parse_and_bind(__string: str) -> None: ... def read_init_file(__filename: StrOrBytesPath | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi index 2d114a7c4f26..d5554344c494 100644 --- a/mypy/typeshed/stdlib/reprlib.pyi +++ b/mypy/typeshed/stdlib/reprlib.pyi @@ -1,10 +1,12 @@ from array import array from collections import deque -from typing import Any, Callable +from collections.abc import Callable +from typing import Any +from typing_extensions import TypeAlias __all__ = ["Repr", "repr", "recursive_repr"] -_ReprFunc = Callable[[Any], str] +_ReprFunc: TypeAlias = Callable[[Any], str] def recursive_repr(fillvalue: str = ...) -> Callable[[_ReprFunc], _ReprFunc]: ... diff --git a/mypy/typeshed/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi index dff781b0c176..709d6f47ff65 100644 --- a/mypy/typeshed/stdlib/sched.pyi +++ b/mypy/typeshed/stdlib/sched.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Callable, NamedTuple +from collections.abc import Callable +from typing import Any, NamedTuple __all__ = ["scheduler"] diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index d4a3656e110e..7cfea9ea0fc1 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import FileDescriptorLike, Self +from collections.abc import Iterable from types import TracebackType -from typing import Any, Iterable +from typing import Any from typing_extensions import final if sys.platform != "win32": diff --git a/mypy/typeshed/stdlib/selectors.pyi b/mypy/typeshed/stdlib/selectors.pyi index 23a94a29a74d..95dfaa41a5c0 100644 --- a/mypy/typeshed/stdlib/selectors.pyi +++ b/mypy/typeshed/stdlib/selectors.pyi @@ -1,9 +1,11 @@ import sys from _typeshed import FileDescriptor, FileDescriptorLike, Self from abc import ABCMeta, abstractmethod -from typing import Any, Mapping, NamedTuple +from collections.abc import Mapping +from typing import Any, NamedTuple +from typing_extensions import TypeAlias -_EventMask = int +_EventMask: TypeAlias = int EVENT_READ: _EventMask EVENT_WRITE: _EventMask diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index 6385011575a4..fe0f80ba26c1 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import Self -from typing import Iterable, TextIO +from collections.abc import Iterable +from typing import TextIO if sys.version_info >= (3, 8): __all__ = ["shlex", "split", "quote", "join"] diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 5fa5f6669f1b..b367a46fe572 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,7 +1,9 @@ import os import sys from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, overload +from collections.abc import Callable, Iterable, Sequence +from typing import Any, AnyStr, NamedTuple, TypeVar, overload +from typing_extensions import TypeAlias __all__ = [ "copyfileobj", @@ -36,7 +38,7 @@ _StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath) _StrPathT = TypeVar("_StrPathT", bound=StrPath) # Return value of some functions that may either return a path-like object that was passed in or # a string -_PathReturn = Any +_PathReturn: TypeAlias = Any class Error(OSError): ... class SameFileError(Error): ... @@ -82,7 +84,7 @@ else: def rmtree(path: StrOrBytesPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... -_CopyFn = Callable[[str, str], None] | Callable[[StrPath, StrPath], None] +_CopyFn: TypeAlias = Callable[[str, str], None] | Callable[[StrPath, StrPath], None] # N.B. shutil.move appears to take bytes arguments, however, # this does not work when dst is (or is within) an existing directory. diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 2defe7995991..893d9d45e4b1 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import structseq +from collections.abc import Callable, Iterable from enum import IntEnum from types import FrameType -from typing import Any, Callable, Iterable, Union -from typing_extensions import Final, final +from typing import Any, Union +from typing_extensions import Final, TypeAlias, final NSIG: int @@ -60,8 +61,8 @@ class Handlers(IntEnum): SIG_DFL: Handlers SIG_IGN: Handlers -_SIGNUM = int | Signals -_HANDLER = Union[Callable[[int, FrameType | None], Any], int, Handlers, None] +_SIGNUM: TypeAlias = int | Signals +_HANDLER: TypeAlias = Union[Callable[[int, FrameType | None], Any], int, Handlers, None] def default_int_handler(__signalnum: int, __frame: FrameType | None) -> None: ... diff --git a/mypy/typeshed/stdlib/site.pyi b/mypy/typeshed/stdlib/site.pyi index a73d188a7e5c..53199db0eaf3 100644 --- a/mypy/typeshed/stdlib/site.pyi +++ b/mypy/typeshed/stdlib/site.pyi @@ -1,5 +1,5 @@ from _typeshed import StrPath -from typing import Iterable +from collections.abc import Iterable PREFIXES: list[str] ENABLE_USER_SITE: bool | None diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index 037f62a8d6e1..fc5a1cb62b16 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -4,13 +4,14 @@ import socket import sys from collections import defaultdict from typing import Any +from typing_extensions import TypeAlias if sys.version_info >= (3, 11): __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy"] else: __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy", "MailmanProxy"] -_Address = tuple[str, int] # (host, port) +_Address: TypeAlias = tuple[str, int] # (host, port) class SMTPChannel(asynchat.async_chat): COMMAND: int diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 3136667dcd11..d90c744c504a 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -1,10 +1,12 @@ import sys from _typeshed import Self +from collections.abc import Sequence from email.message import Message as _Message from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Pattern, Protocol, Sequence, overload +from typing import Any, Pattern, Protocol, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 7): __all__ = [ @@ -40,10 +42,10 @@ else: "SMTP_SSL", ] -_Reply = tuple[int, bytes] -_SendErrs = dict[str, _Reply] +_Reply: TypeAlias = tuple[int, bytes] +_SendErrs: TypeAlias = dict[str, _Reply] # Should match source_address for socket.create_connection -_SourceAddress = tuple[bytearray | bytes | str, int] +_SourceAddress: TypeAlias = tuple[bytearray | bytes | str, int] SMTP_PORT: int SMTP_SSL_PORT: int diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index 9bdd8ccfe31f..20ff5daa718e 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -1,8 +1,10 @@ import sys import types from _typeshed import Self +from collections.abc import Callable from socket import socket as _socket -from typing import Any, BinaryIO, Callable, ClassVar, Union +from typing import Any, BinaryIO, ClassVar, Union +from typing_extensions import TypeAlias if sys.platform == "win32": __all__ = [ @@ -36,8 +38,8 @@ else: "ThreadingUnixDatagramServer", ] -_RequestType = Union[_socket, tuple[bytes, _socket]] -_AddressType = Union[tuple[str, int], str] +_RequestType: TypeAlias = Union[_socket, tuple[bytes, _socket]] +_AddressType: TypeAlias = Union[tuple[str, int], str] # This can possibly be generic at some point: class BaseServer: diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 05e5a176d8ff..87e843c5fb26 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,11 +1,23 @@ +import sqlite3 import sys -from _typeshed import Self, StrOrBytesPath +from _typeshed import ReadableBuffer, Self, StrOrBytesPath, SupportsLenAndGetItem +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping from datetime import date, datetime, time from types import TracebackType -from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, TypeVar -from typing_extensions import Literal, final +from typing import Any, Generic, Protocol, TypeVar, overload +from typing_extensions import Literal, SupportsIndex, TypeAlias, final _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_CursorT = TypeVar("_CursorT", bound=Cursor) +_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None +# Data that is passed through adapters can be of any type accepted by an adapter. +_AdaptedInputData: TypeAlias = _SqliteData | Any +# The Mapping must really be a dict, but making it invariant is too annoying. +_Parameters: TypeAlias = SupportsLenAndGetItem[_AdaptedInputData] | Mapping[str, _AdaptedInputData] +_SqliteOutputData: TypeAlias = str | bytes | int | float | None +_Adapter: TypeAlias = Callable[[_T], _SqliteData] +_Converter: TypeAlias = Callable[[bytes], Any] paramstyle: str threadsafety: int @@ -80,43 +92,144 @@ if sys.version_info >= (3, 7): SQLITE_SELECT: int SQLITE_TRANSACTION: int SQLITE_UPDATE: int -adapters: Any -converters: Any +adapters: dict[tuple[type[Any], type[Any]], _Adapter[Any]] +converters: dict[str, _Converter] sqlite_version: str version: str -# TODO: adapt needs to get probed -def adapt(obj, protocol, alternate): ... +if sys.version_info >= (3, 11): + SQLITE_ABORT: int + SQLITE_ABORT_ROLLBACK: int + SQLITE_AUTH: int + SQLITE_AUTH_USER: int + SQLITE_BUSY: int + SQLITE_BUSY_RECOVERY: int + SQLITE_BUSY_SNAPSHOT: int + SQLITE_BUSY_TIMEOUT: int + SQLITE_CANTOPEN: int + SQLITE_CANTOPEN_CONVPATH: int + SQLITE_CANTOPEN_DIRTYWAL: int + SQLITE_CANTOPEN_FULLPATH: int + SQLITE_CANTOPEN_ISDIR: int + SQLITE_CANTOPEN_NOTEMPDIR: int + SQLITE_CANTOPEN_SYMLINK: int + SQLITE_CONSTRAINT: int + SQLITE_CONSTRAINT_CHECK: int + SQLITE_CONSTRAINT_COMMITHOOK: int + SQLITE_CONSTRAINT_FOREIGNKEY: int + SQLITE_CONSTRAINT_FUNCTION: int + SQLITE_CONSTRAINT_NOTNULL: int + SQLITE_CONSTRAINT_PINNED: int + SQLITE_CONSTRAINT_PRIMARYKEY: int + SQLITE_CONSTRAINT_ROWID: int + SQLITE_CONSTRAINT_TRIGGER: int + SQLITE_CONSTRAINT_UNIQUE: int + SQLITE_CONSTRAINT_VTAB: int + SQLITE_CORRUPT: int + SQLITE_CORRUPT_INDEX: int + SQLITE_CORRUPT_SEQUENCE: int + SQLITE_CORRUPT_VTAB: int + SQLITE_EMPTY: int + SQLITE_ERROR: int + SQLITE_ERROR_MISSING_COLLSEQ: int + SQLITE_ERROR_RETRY: int + SQLITE_ERROR_SNAPSHOT: int + SQLITE_FORMAT: int + SQLITE_FULL: int + SQLITE_INTERNAL: int + SQLITE_INTERRUPT: int + SQLITE_IOERR: int + SQLITE_IOERR_ACCESS: int + SQLITE_IOERR_AUTH: int + SQLITE_IOERR_BEGIN_ATOMIC: int + SQLITE_IOERR_BLOCKED: int + SQLITE_IOERR_CHECKRESERVEDLOCK: int + SQLITE_IOERR_CLOSE: int + SQLITE_IOERR_COMMIT_ATOMIC: int + SQLITE_IOERR_CONVPATH: int + SQLITE_IOERR_CORRUPTFS: int + SQLITE_IOERR_DATA: int + SQLITE_IOERR_DELETE: int + SQLITE_IOERR_DELETE_NOENT: int + SQLITE_IOERR_DIR_CLOSE: int + SQLITE_IOERR_DIR_FSYNC: int + SQLITE_IOERR_FSTAT: int + SQLITE_IOERR_FSYNC: int + SQLITE_IOERR_GETTEMPPATH: int + SQLITE_IOERR_LOCK: int + SQLITE_IOERR_MMAP: int + SQLITE_IOERR_NOMEM: int + SQLITE_IOERR_RDLOCK: int + SQLITE_IOERR_READ: int + SQLITE_IOERR_ROLLBACK_ATOMIC: int + SQLITE_IOERR_SEEK: int + SQLITE_IOERR_SHMLOCK: int + SQLITE_IOERR_SHMMAP: int + SQLITE_IOERR_SHMOPEN: int + SQLITE_IOERR_SHMSIZE: int + SQLITE_IOERR_SHORT_READ: int + SQLITE_IOERR_TRUNCATE: int + SQLITE_IOERR_UNLOCK: int + SQLITE_IOERR_VNODE: int + SQLITE_IOERR_WRITE: int + SQLITE_LOCKED: int + SQLITE_LOCKED_SHAREDCACHE: int + SQLITE_LOCKED_VTAB: int + SQLITE_MISMATCH: int + SQLITE_MISUSE: int + SQLITE_NOLFS: int + SQLITE_NOMEM: int + SQLITE_NOTADB: int + SQLITE_NOTFOUND: int + SQLITE_NOTICE: int + SQLITE_NOTICE_RECOVER_ROLLBACK: int + SQLITE_NOTICE_RECOVER_WAL: int + SQLITE_OK_LOAD_PERMANENTLY: int + SQLITE_OK_SYMLINK: int + SQLITE_PERM: int + SQLITE_PROTOCOL: int + SQLITE_RANGE: int + SQLITE_READONLY: int + SQLITE_READONLY_CANTINIT: int + SQLITE_READONLY_CANTLOCK: int + SQLITE_READONLY_DBMOVED: int + SQLITE_READONLY_DIRECTORY: int + SQLITE_READONLY_RECOVERY: int + SQLITE_READONLY_ROLLBACK: int + SQLITE_ROW: int + SQLITE_SCHEMA: int + SQLITE_TOOBIG: int + SQLITE_WARNING: int + SQLITE_WARNING_AUTOINDEX: int + +# Can take or return anything depending on what's in the registry. +@overload +def adapt(__obj: Any, __proto: Any) -> Any: ... +@overload +def adapt(__obj: Any, __proto: Any, __alt: _T) -> Any | _T: ... def complete_statement(statement: str) -> bool: ... if sys.version_info >= (3, 7): - def connect( - database: StrOrBytesPath, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., - ) -> Connection: ... - + _DatabaseArg: TypeAlias = StrOrBytesPath else: - def connect( - database: bytes | str, - timeout: float = ..., - detect_types: int = ..., - isolation_level: str | None = ..., - check_same_thread: bool = ..., - factory: type[Connection] | None = ..., - cached_statements: int = ..., - uri: bool = ..., - ) -> Connection: ... + _DatabaseArg: TypeAlias = bytes | str +def connect( + database: _DatabaseArg, + timeout: float = ..., + detect_types: int = ..., + isolation_level: str | None = ..., + check_same_thread: bool = ..., + factory: type[Connection] | None = ..., + cached_statements: int = ..., + uri: bool = ..., +) -> Connection: ... def enable_callback_tracebacks(__enable: bool) -> None: ... + +# takes a pos-or-keyword argument because there is a C wrapper def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... -def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... +def register_adapter(__type: type[_T], __caster: _Adapter[_T]) -> None: ... +def register_converter(__name: str, __converter: _Converter) -> None: ... if sys.version_info < (3, 8): class Cache: @@ -125,40 +238,104 @@ if sys.version_info < (3, 8): def get(self, *args, **kwargs) -> None: ... class _AggregateProtocol(Protocol): - def step(self, value: int) -> None: ... + def step(self, __value: int) -> object: ... def finalize(self) -> int: ... +class _SingleParamWindowAggregateClass(Protocol): + def step(self, __param: Any) -> object: ... + def inverse(self, __param: Any) -> object: ... + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +class _AnyParamWindowAggregateClass(Protocol): + def step(self, *args: Any) -> object: ... + def inverse(self, *args: Any) -> object: ... + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +class _WindowAggregateClass(Protocol): + step: Callable[..., object] + inverse: Callable[..., object] + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + class Connection: - DataError: Any - DatabaseError: Any - Error: Any - IntegrityError: Any - InterfaceError: Any - InternalError: Any - NotSupportedError: Any - OperationalError: Any - ProgrammingError: Any - Warning: Any - in_transaction: Any - isolation_level: Any + @property + def DataError(self) -> type[sqlite3.DataError]: ... + @property + def DatabaseError(self) -> type[sqlite3.DatabaseError]: ... + @property + def Error(self) -> type[sqlite3.Error]: ... + @property + def IntegrityError(self) -> type[sqlite3.IntegrityError]: ... + @property + def InterfaceError(self) -> type[sqlite3.InterfaceError]: ... + @property + def InternalError(self) -> type[sqlite3.InternalError]: ... + @property + def NotSupportedError(self) -> type[sqlite3.NotSupportedError]: ... + @property + def OperationalError(self) -> type[sqlite3.OperationalError]: ... + @property + def ProgrammingError(self) -> type[sqlite3.ProgrammingError]: ... + @property + def Warning(self) -> type[sqlite3.Warning]: ... + @property + def in_transaction(self) -> bool: ... + isolation_level: str | None # one of '', 'DEFERRED', 'IMMEDIATE' or 'EXCLUSIVE' + @property + def total_changes(self) -> int: ... row_factory: Any text_factory: Any - total_changes: Any - def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __init__( + self, + database: _DatabaseArg, + timeout: float = ..., + detect_types: int = ..., + isolation_level: str | None = ..., + check_same_thread: bool = ..., + factory: type[Connection] | None = ..., + cached_statements: int = ..., + uri: bool = ..., + ) -> None: ... def close(self) -> None: ... + if sys.version_info >= (3, 11): + def blobopen(self, __table: str, __column: str, __row: int, *, readonly: bool = ..., name: str = ...) -> Blob: ... + def commit(self) -> None: ... def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... - def create_collation(self, __name: str, __callback: Any) -> None: ... + if sys.version_info >= (3, 11): + # num_params determines how many params will be passed to the aggregate class. We provide an overload + # for the case where num_params = 1, which is expected to be the common case. + @overload + def create_window_function( + self, __name: str, __num_params: Literal[1], __aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None + ) -> None: ... + # And for num_params = -1, which means the aggregate must accept any number of parameters. + @overload + def create_window_function( + self, __name: str, __num_params: Literal[-1], __aggregate_class: Callable[[], _AnyParamWindowAggregateClass] | None + ) -> None: ... + @overload + def create_window_function( + self, __name: str, __num_params: int, __aggregate_class: Callable[[], _WindowAggregateClass] | None + ) -> None: ... + + def create_collation(self, __name: str, __callback: Callable[[str, str], int | SupportsIndex] | None) -> None: ... if sys.version_info >= (3, 8): - def create_function(self, name: str, narg: int, func: Any, *, deterministic: bool = ...) -> None: ... + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData], *, deterministic: bool = ... + ) -> None: ... else: - def create_function(self, name: str, num_params: int, func: Any) -> None: ... + def create_function(self, name: str, num_params: int, func: Callable[..., _SqliteData]) -> None: ... - def cursor(self, cursorClass: type | None = ...) -> Cursor: ... - def execute(self, sql: str, parameters: Iterable[Any] = ...) -> Cursor: ... - # TODO: please check in executemany() if seq_of_parameters type is possible like this - def executemany(self, __sql: str, __parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: bytes | str) -> Cursor: ... + @overload + def cursor(self, cursorClass: None = ...) -> Cursor: ... + @overload + def cursor(self, cursorClass: Callable[[], _CursorT]) -> _CursorT: ... + def execute(self, sql: str, parameters: _Parameters = ...) -> Cursor: ... + def executemany(self, __sql: str, __parameters: Iterable[_Parameters]) -> Cursor: ... + def executescript(self, __sql_script: str) -> Cursor: ... def interrupt(self) -> None: ... def iterdump(self) -> Generator[str, None, None]: ... def rollback(self) -> None: ... @@ -169,8 +346,8 @@ class Connection: def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... # enable_load_extension and load_extension is not available on python distributions compiled # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 - def enable_load_extension(self, enabled: bool) -> None: ... - def load_extension(self, path: str) -> None: ... + def enable_load_extension(self, __enabled: bool) -> None: ... + def load_extension(self, __name: str) -> None: ... if sys.version_info >= (3, 7): def backup( self, @@ -181,30 +358,38 @@ class Connection: name: str = ..., sleep: float = ..., ) -> None: ... + if sys.version_info >= (3, 11): + def setlimit(self, __category: int, __limit: int) -> int: ... + def getlimit(self, __category: int) -> int: ... + def serialize(self, *, name: str = ...) -> bytes: ... + def deserialize(self, __data: ReadableBuffer, *, name: str = ...) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __call__(self, __sql: str) -> _Statement: ... def __enter__(self: Self) -> Self: ... def __exit__( self, __type: type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None ) -> Literal[False]: ... class Cursor(Iterator[Any]): - arraysize: Any - connection: Any - description: Any - lastrowid: Any - row_factory: Any - rowcount: int - # TODO: Cursor class accepts exactly 1 argument - # required type is sqlite3.Connection (which is imported as _Connection) - # however, the name of the __init__ variable is unknown - def __init__(self, *args: Any, **kwargs: Any) -> None: ... + arraysize: int + @property + def connection(self) -> Connection: ... + @property + def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | None: ... + @property + def lastrowid(self) -> int | None: ... + row_factory: Callable[[Cursor, Row[Any]], object] | None + @property + def rowcount(self) -> int: ... + def __init__(self, __cursor: Connection) -> None: ... def close(self) -> None: ... - def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... - def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... - def executescript(self, __sql_script: bytes | str) -> Cursor: ... + def execute(self: Self, __sql: str, __parameters: _Parameters = ...) -> Self: ... + def executemany(self: Self, __sql: str, __seq_of_parameters: Iterable[_Parameters]) -> Self: ... + def executescript(self, __sql_script: str) -> Cursor: ... def fetchall(self) -> list[Any]: ... def fetchmany(self, size: int | None = ...) -> list[Any]: ... + # Returns either a row (as created by the row_factory) or None, but + # putting None in the return annotation causes annoying false positives. def fetchone(self) -> Any: ... def setinputsizes(self, __sizes: object) -> None: ... # does nothing def setoutputsize(self, __size: object, __column: object = ...) -> None: ... # does nothing @@ -225,31 +410,53 @@ class InternalError(DatabaseError): ... class NotSupportedError(DatabaseError): ... class OperationalError(DatabaseError): ... -OptimizedUnicode = str +if sys.version_info < (3, 10): + OptimizedUnicode = str @final class PrepareProtocol: - def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __init__(self, *args: object, **kwargs: object) -> None: ... class ProgrammingError(DatabaseError): ... -class Row: - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def keys(self): ... - def __eq__(self, __other): ... - def __ge__(self, __other): ... - def __getitem__(self, __index): ... - def __gt__(self, __other): ... - def __hash__(self): ... - def __iter__(self): ... - def __le__(self, __other): ... - def __len__(self): ... - def __lt__(self, __other): ... - def __ne__(self, __other): ... +class Row(Generic[_T_co]): + def __init__(self, __cursor: Cursor, __data: tuple[_T_co, ...]) -> None: ... + def keys(self) -> list[str]: ... + @overload + def __getitem__(self, __index: int | str) -> _T_co: ... + @overload + def __getitem__(self, __index: slice) -> tuple[_T_co, ...]: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __len__(self) -> int: ... + # These return NotImplemented for anything that is not a Row. + def __eq__(self, __other: object) -> bool: ... + def __ge__(self, __other: object) -> bool: ... + def __gt__(self, __other: object) -> bool: ... + def __le__(self, __other: object) -> bool: ... + def __lt__(self, __other: object) -> bool: ... + def __ne__(self, __other: object) -> bool: ... -if sys.version_info < (3, 8): +if sys.version_info >= (3, 8): + @final + class _Statement: ... + +else: @final class Statement: def __init__(self, *args, **kwargs): ... + _Statement: TypeAlias = Statement class Warning(Exception): ... + +if sys.version_info >= (3, 11): + class Blob: + def close(self) -> None: ... + def read(self, __length: int = ...) -> bytes: ... + def write(self, __data: bytes) -> None: ... + def tell(self) -> int: ... + # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END + def seek(self, __offset: int, __whence: int = ...) -> None: ... + def __len__(self) -> int: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, __typ: object, __val: object, __tb: object) -> Literal[False]: ... diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index 05e71c255967..0958e73f5176 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -1,7 +1,9 @@ import sys +from collections.abc import Iterable from sre_constants import * from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Iterable, Match, Pattern as _Pattern, overload +from typing import Any, Match, Pattern as _Pattern, overload +from typing_extensions import TypeAlias SPECIAL_CHARS: str REPEAT_CHARS: str @@ -33,16 +35,16 @@ class _State: def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... if sys.version_info >= (3, 8): - State = _State + State: TypeAlias = _State else: - Pattern = _State + Pattern: TypeAlias = _State -_OpSubpatternType = tuple[int | None, int, int, SubPattern] -_OpGroupRefExistsType = tuple[int, SubPattern, SubPattern] -_OpInType = list[tuple[_NIC, int]] -_OpBranchType = tuple[None, list[SubPattern]] -_AvType = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType -_CodeType = tuple[_NIC, _AvType] +_OpSubpatternType: TypeAlias = tuple[int | None, int, int, SubPattern] +_OpGroupRefExistsType: TypeAlias = tuple[int, SubPattern, SubPattern] +_OpInType: TypeAlias = list[tuple[_NIC, int]] +_OpBranchType: TypeAlias = tuple[None, list[SubPattern]] +_AvType: TypeAlias = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType +_CodeType: TypeAlias = tuple[_NIC, _AvType] class SubPattern: data: list[_CodeType] @@ -87,8 +89,8 @@ class Tokenizer: def fix_flags(src: str | bytes, flags: int) -> int: ... -_TemplateType = tuple[list[tuple[int, int]], list[str | None]] -_TemplateByteType = tuple[list[tuple[int, int]], list[bytes | None]] +_TemplateType: TypeAlias = tuple[list[tuple[int, int]], list[str | None]] +_TemplateByteType: TypeAlias = tuple[list[tuple[int, int]], list[bytes | None]] if sys.version_info >= (3, 8): def parse(str: str, flags: int = ..., state: State | None = ...) -> SubPattern: ... @overload diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index b7fe6914db0e..8445435fa346 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -2,17 +2,18 @@ import enum import socket import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import Any, Callable, Iterable, NamedTuple, Union, overload -from typing_extensions import Literal, TypedDict, final - -_PCTRTT = tuple[tuple[str, str], ...] -_PCTRTTT = tuple[_PCTRTT, ...] -_PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] -_PeerCertRetType = _PeerCertRetDictType | bytes | None -_EnumRetType = list[tuple[bytes, str, set[str] | bool]] -_PasswordType = Union[Callable[[], str | bytes], str, bytes] - -_SrvnmeCbType = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] +from collections.abc import Callable, Iterable +from typing import Any, NamedTuple, Union, overload +from typing_extensions import Literal, TypeAlias, TypedDict, final + +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] +_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType: TypeAlias = _PeerCertRetDictType | bytes | None +_EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] +_PasswordType: TypeAlias = Union[Callable[[], str | bytes], str, bytes] + +_SrvnmeCbType: TypeAlias = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] class _Cipher(TypedDict): aead: bool diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 446a778794f1..540ccfcaaa8c 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import Self, SupportsRichComparisonT +from collections.abc import Hashable, Iterable, Sequence from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar -from typing_extensions import Literal +from typing import Any, NamedTuple, SupportsFloat, TypeVar +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 10): __all__ = [ @@ -65,7 +66,7 @@ else: ] # Most functions in this module accept homogeneous collections of one of these types -_Number = float | Decimal | Fraction +_Number: TypeAlias = float | Decimal | Fraction _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) # Used in mode, multimode diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 535f38545132..4404bde8bc4f 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -1,6 +1,7 @@ import sys +from collections.abc import Iterable, Mapping, Sequence from re import RegexFlag -from typing import Any, Iterable, Mapping, Sequence +from typing import Any if sys.version_info >= (3, 8): from re import Pattern diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index 1f6c45a23c0a..59c66ad2f167 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer -from typing import Any, Iterator +from collections.abc import Iterator +from typing import Any __all__ = ["calcsize", "pack", "pack_into", "unpack", "unpack_from", "iter_unpack", "Struct", "error"] diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index ced2e708f8ff..98bbf7d33f90 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import Self, StrOrBytesPath +from collections.abc import Callable, Iterable, Mapping, Sequence from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload -from typing_extensions import Literal +from typing import IO, Any, AnyStr, Generic, TypeVar, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -102,18 +103,18 @@ else: # reveal_type(x) # bytes, based on the overloads # except TimeoutError as e: # reveal_type(e.cmd) # Any, but morally is _CMD -_FILE = None | int | IO[Any] -_TXT = bytes | str +_FILE: TypeAlias = None | int | IO[Any] +_TXT: TypeAlias = bytes | str if sys.version_info >= (3, 8): - _CMD = StrOrBytesPath | Sequence[StrOrBytesPath] + _CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath] else: # Python 3.6 doesn't support _CMD being a single PathLike. # See: https://bugs.python.org/issue31961 - _CMD = _TXT | Sequence[StrOrBytesPath] + _CMD: TypeAlias = _TXT | Sequence[StrOrBytesPath] if sys.platform == "win32": - _ENV = Mapping[str, str] + _ENV: TypeAlias = Mapping[str, str] else: - _ENV = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath] + _ENV: TypeAlias = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath] _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index 73aa8999caa1..5b21cb03d4a3 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import Self from typing import IO, Any, NamedTuple, NoReturn, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias -_File = str | IO[bytes] +_File: TypeAlias = str | IO[bytes] class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index 91e95270901e..7a95fe5e445f 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Sequence +from collections.abc import Sequence +from typing import Any __all__ = ["symtable", "SymbolTable", "Class", "Function", "Symbol"] diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 4fca35a2c82d..92b806e04420 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -1,18 +1,17 @@ import sys -from _typeshed import structseq +from _typeshed import OptExcInfo, structseq from builtins import object as _object +from collections.abc import AsyncGenerator, Callable, Coroutine, Sequence from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType -from typing import Any, AsyncGenerator, Callable, Coroutine, NoReturn, Protocol, Sequence, TextIO, TypeVar, Union, overload -from typing_extensions import Literal, final +from typing import Any, NoReturn, Protocol, TextIO, TypeVar, overload +from typing_extensions import Literal, TypeAlias, final _T = TypeVar("_T") -# The following type alias are stub-only and do not exist during runtime -_ExcInfo = tuple[type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, tuple[None, None, None]] +_OptExcInfo: TypeAlias = OptExcInfo # TODO: obsolete, remove fall 2022 or later # Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` class _MetaPathFinder(Protocol): @@ -76,16 +75,16 @@ _xoptions: dict[Any, Any] # Type alias used as a mixin for structseq classes that cannot be instantiated at runtime # This can't be represented in the type system, so we just use `structseq[Any]` -_uninstantiable_structseq = structseq[Any] +_uninstantiable_structseq: TypeAlias = structseq[Any] flags: _flags if sys.version_info >= (3, 10): - _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int, int] + _FlagTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int, int] elif sys.version_info >= (3, 7): - _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int] + _FlagTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int] else: - _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int] + _FlagTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int] @final class _flags(_uninstantiable_structseq, _FlagTuple): @@ -217,7 +216,7 @@ def _getframe(__depth: int = ...) -> FrameType: ... def _debugmallocstats() -> None: ... def __displayhook__(__value: object) -> None: ... def __excepthook__(__exctype: type[BaseException], __value: BaseException, __traceback: TracebackType | None) -> None: ... -def exc_info() -> _OptExcInfo: ... +def exc_info() -> OptExcInfo: ... # sys.exit() accepts an optional argument of anything printable def exit(__status: object = ...) -> NoReturn: ... @@ -237,12 +236,12 @@ def getsizeof(obj: object) -> int: ... def getsizeof(obj: object, default: int) -> int: ... def getswitchinterval() -> float: ... -_ProfileFunc = Callable[[FrameType, str, Any], Any] +_ProfileFunc: TypeAlias = Callable[[FrameType, str, Any], Any] def getprofile() -> _ProfileFunc | None: ... def setprofile(profilefunc: _ProfileFunc | None) -> None: ... -_TraceFunc = Callable[[FrameType, str, Any], Callable[[FrameType, str, Any], Any] | None] +_TraceFunc: TypeAlias = Callable[[FrameType, str, Any], Callable[[FrameType, str, Any], Any] | None] def gettrace() -> _TraceFunc | None: ... def settrace(tracefunc: _TraceFunc | None) -> None: ... @@ -309,7 +308,7 @@ if sys.version_info >= (3, 8): def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... def audit(__event: str, *args: Any) -> None: ... -_AsyncgenHook = Callable[[AsyncGenerator[Any, Any]], None] | None +_AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None @final class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): @@ -330,6 +329,6 @@ if sys.version_info >= (3, 7): def set_coroutine_origin_tracking_depth(depth: int) -> None: ... if sys.version_info < (3, 8): - _CoroWrapper = Callable[[Coroutine[Any, Any, Any]], Any] + _CoroWrapper: TypeAlias = Callable[[Coroutine[Any, Any, Any]], Any] def set_coroutine_wrapper(__wrapper: _CoroWrapper) -> None: ... def get_coroutine_wrapper() -> _CoroWrapper: ... diff --git a/mypy/typeshed/stdlib/tabnanny.pyi b/mypy/typeshed/stdlib/tabnanny.pyi index 020100031c14..8a8592f44124 100644 --- a/mypy/typeshed/stdlib/tabnanny.pyi +++ b/mypy/typeshed/stdlib/tabnanny.pyi @@ -1,5 +1,5 @@ from _typeshed import StrOrBytesPath -from typing import Iterable +from collections.abc import Iterable __all__ = ["check", "NannyNag", "process_tokens"] diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 2837c46e1d21..364bcad0683f 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -2,7 +2,7 @@ import bz2 import io import sys from _typeshed import Self, StrOrBytesPath, StrPath -from builtins import type as Type # alias to avoid name clashes with fields named "type" +from builtins import list as _list, type as Type # aliases to avoid name clashes with fields named "type" or "list" from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType @@ -109,8 +109,6 @@ def open( class ExFileObject(io.BufferedReader): def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... -_list = list # conflicts with method name - class TarFile: OPEN_METH: Mapping[str, str] name: StrOrBytesPath | None diff --git a/mypy/typeshed/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi index 359be6e49781..8edbd155f61c 100644 --- a/mypy/typeshed/stdlib/telnetlib.pyi +++ b/mypy/typeshed/stdlib/telnetlib.pyi @@ -1,7 +1,8 @@ import socket from _typeshed import Self +from collections.abc import Callable, Sequence from types import TracebackType -from typing import Any, Callable, Match, Pattern, Sequence +from typing import Any, Match, Pattern __all__ = ["Telnet"] diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 19a4dbee2ee7..4f2b4a545ff7 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -1,9 +1,10 @@ import os import sys from _typeshed import Self +from collections.abc import Iterable, Iterator from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, overload -from typing_extensions import Literal +from typing import IO, Any, AnyStr, Generic, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -29,7 +30,7 @@ TMP_MAX: int tempdir: str | None template: str -_DirT = AnyStr | os.PathLike[AnyStr] +_DirT: TypeAlias = AnyStr | os.PathLike[AnyStr] if sys.version_info >= (3, 8): @overload diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index c6a90df31b59..b2423304b930 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import FileDescriptorLike from typing import Any +from typing_extensions import TypeAlias if sys.platform != "win32": - _Attr = list[int | list[bytes | int]] + _Attr: TypeAlias = list[int | list[bytes | int]] # TODO constants not really documented B0: int diff --git a/mypy/typeshed/stdlib/textwrap.pyi b/mypy/typeshed/stdlib/textwrap.pyi index aeb1d87141be..5a61dfedb380 100644 --- a/mypy/typeshed/stdlib/textwrap.pyi +++ b/mypy/typeshed/stdlib/textwrap.pyi @@ -1,4 +1,5 @@ -from typing import Callable, Pattern +from collections.abc import Callable +from typing import Pattern __all__ = ["TextWrapper", "wrap", "fill", "dedent", "indent", "shorten"] diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index c3fa57fafa7c..231018ca731a 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,11 +1,13 @@ import sys +from collections.abc import Callable, Iterable, Mapping from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, TypeVar +from typing import Any, TypeVar +from typing_extensions import TypeAlias # TODO recursive type -_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] +_TF: TypeAlias = Callable[[FrameType, str, Any], Callable[..., Any] | None] -_PF = Callable[[FrameType, str, Any], None] +_PF: TypeAlias = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 25f8d7056cd8..cceb7c8ca874 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import structseq from typing import Any, Protocol -from typing_extensions import Final, Literal, final +from typing_extensions import Final, Literal, TypeAlias, final -_TimeTuple = tuple[int, int, int, int, int, int, int, int, int] +_TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int] altzone: int daylight: int diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index bfaea728ff42..076b2c54f991 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -1,9 +1,11 @@ -from typing import IO, Any, Callable, Sequence +from collections.abc import Callable, Sequence +from typing import IO, Any +from typing_extensions import TypeAlias __all__ = ["Timer", "timeit", "repeat", "default_timer"] -_Timer = Callable[[], float] -_Stmt = str | Callable[[], Any] +_Timer: TypeAlias = Callable[[], float] +_Stmt: TypeAlias = str | Callable[[], Any] default_timer: _Timer diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 2a6172ba46a3..66c52107067d 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -1,12 +1,13 @@ import _tkinter import sys from _typeshed import StrOrBytesPath +from collections.abc import Callable, Mapping, Sequence from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Callable, Generic, Mapping, Protocol, Sequence, TypeVar, Union, overload -from typing_extensions import Literal, TypedDict +from typing import Any, Generic, Protocol, TypeVar, Union, overload +from typing_extensions import Literal, TypeAlias, TypedDict if sys.version_info >= (3, 9): __all__ = [ @@ -171,29 +172,31 @@ EXCEPTION = _tkinter.EXCEPTION # Some widgets have an option named -compound that accepts different values # than the _Compound defined here. Many other options have similar things. -_Anchor = Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] # manual page: Tk_GetAnchor -_Bitmap = str # manual page: Tk_GetBitmap -_ButtonCommand = str | Callable[[], Any] # accepts string of tcl code, return value is returned from Button.invoke() -_CanvasItemId = int -_Color = str # typically '#rrggbb', '#rgb' or color names. -_Compound = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' -_Cursor = Union[str, tuple[str], tuple[str, str], tuple[str, str, str], tuple[str, str, str, str]] # manual page: Tk_GetCursor -_EntryValidateCommand = ( +_Anchor: TypeAlias = Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] # manual page: Tk_GetAnchor +_Bitmap: TypeAlias = str # manual page: Tk_GetBitmap +_ButtonCommand: TypeAlias = str | Callable[[], Any] # accepts string of tcl code, return value is returned from Button.invoke() +_CanvasItemId: TypeAlias = int +_Color: TypeAlias = str # typically '#rrggbb', '#rgb' or color names. +_Compound: TypeAlias = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' +_Cursor: TypeAlias = Union[ + str, tuple[str], tuple[str, str], tuple[str, str, str], tuple[str, str, str, str] +] # manual page: Tk_GetCursor +_EntryValidateCommand: TypeAlias = ( str | list[str] | tuple[str, ...] | Callable[[], bool] ) # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] -_GridIndex = int | str | Literal["all"] -_ImageSpec = _Image | str # str can be from e.g. tkinter.image_names() -_Padding = Union[ +_GridIndex: TypeAlias = int | str | Literal["all"] +_ImageSpec: TypeAlias = _Image | str # str can be from e.g. tkinter.image_names() +_Padding: TypeAlias = Union[ _ScreenUnits, tuple[_ScreenUnits], tuple[_ScreenUnits, _ScreenUnits], tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits], tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], ] -_Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief -_ScreenUnits = str | float # Often the right type instead of int. Manual page: Tk_GetPixels -_XYScrollCommand = str | Callable[[float, float], Any] # -xscrollcommand and -yscrollcommand in 'options' manual page -_TakeFocusValue = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' +_Relief: TypeAlias = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief +_ScreenUnits: TypeAlias = str | float # Often the right type instead of int. Manual page: Tk_GetPixels +_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' class EventType(str, Enum): Activate: str @@ -263,7 +266,7 @@ class Event(Generic[_W_co]): def NoDefaultRoot() -> None: ... -_TraceMode = Literal["array", "read", "write", "unset"] +_TraceMode: TypeAlias = Literal["array", "read", "write", "unset"] class Variable: def __init__(self, master: Misc | None = ..., value: Any | None = ..., name: str | None = ...) -> None: ... @@ -1696,7 +1699,7 @@ class Checkbutton(Widget): def select(self) -> None: ... def toggle(self) -> None: ... -_EntryIndex = str | int # "INDICES" in manual page +_EntryIndex: TypeAlias = str | int # "INDICES" in manual page class Entry(Widget, XView): def __init__( @@ -2054,7 +2057,7 @@ class Listbox(Widget, XView, YView): def itemconfigure(self, index, cnf: Any | None = ..., **kw): ... itemconfig: Any -_MenuIndex = str | int +_MenuIndex: TypeAlias = str | int class Menu(Widget): def __init__( @@ -2740,7 +2743,7 @@ class Scrollbar(Widget): def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ... def set(self, first: float, last: float) -> None: ... -_TextIndex = _tkinter.Tcl_Obj | str | float | Misc +_TextIndex: TypeAlias = _tkinter.Tcl_Obj | str | float | Misc class Text(Widget, XView, YView): def __init__( diff --git a/mypy/typeshed/stdlib/tkinter/commondialog.pyi b/mypy/typeshed/stdlib/tkinter/commondialog.pyi index 1c5fb0f53706..faebcc33955e 100644 --- a/mypy/typeshed/stdlib/tkinter/commondialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/commondialog.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, ClassVar, Mapping +from collections.abc import Mapping +from typing import Any, ClassVar if sys.version_info >= (3, 9): __all__ = ["Dialog"] diff --git a/mypy/typeshed/stdlib/tkinter/dialog.pyi b/mypy/typeshed/stdlib/tkinter/dialog.pyi index f9c8487c44a9..9ced7a208808 100644 --- a/mypy/typeshed/stdlib/tkinter/dialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/dialog.pyi @@ -1,6 +1,7 @@ import sys +from collections.abc import Mapping from tkinter import Widget -from typing import Any, Mapping +from typing import Any if sys.version_info >= (3, 9): __all__ = ["Dialog"] diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index dc0e01a6d1d1..2815289e81c3 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import StrOrBytesPath +from collections.abc import Iterable from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog -from typing import IO, Any, ClassVar, Iterable +from typing import IO, Any, ClassVar from typing_extensions import Literal if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 4b0101b32788..dff84e9fac78 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -2,7 +2,7 @@ import _tkinter import sys import tkinter from typing import Any, overload -from typing_extensions import Literal, TypedDict +from typing_extensions import Literal, TypeAlias, TypedDict if sys.version_info >= (3, 9): __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] @@ -12,7 +12,7 @@ ROMAN: Literal["roman"] BOLD: Literal["bold"] ITALIC: Literal["italic"] -_FontDescription = ( +_FontDescription: TypeAlias = ( str # "Helvetica 12" | Font # A font object constructed in Python | list[Any] # ("Helvetica", 12, BOLD) diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index c48b5cd7aa0d..7ca8f9b800ce 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1,9 +1,10 @@ import _tkinter import sys import tkinter +from collections.abc import Callable from tkinter.font import _FontDescription -from typing import Any, Callable, overload -from typing_extensions import Literal, TypedDict +from typing import Any, overload +from typing_extensions import Literal, TypeAlias, TypedDict if sys.version_info >= (3, 7): __all__ = [ @@ -65,7 +66,7 @@ def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... def setup_master(master: Any | None = ...): ... # from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound -_TtkCompound = Literal["text", "image", tkinter._Compound] +_TtkCompound: TypeAlias = Literal["text", "image", tkinter._Compound] class Style: master: Any @@ -972,7 +973,7 @@ class _TreeviewColumnDict(TypedDict): anchor: tkinter._Anchor id: str -_TreeviewColumnId = int | str # manual page: "COLUMN IDENTIFIERS" +_TreeviewColumnId: TypeAlias = int | str # manual page: "COLUMN IDENTIFIERS" class Treeview(Widget, tkinter.XView, tkinter.YView): def __init__( diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 7b17e8de6153..dea83263b550 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -1,8 +1,10 @@ import sys from _typeshed import StrOrBytesPath from builtins import open as _builtin_open +from collections.abc import Callable, Generator, Iterable, Sequence from token import * -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO +from typing import Any, NamedTuple, Pattern, TextIO +from typing_extensions import TypeAlias if sys.version_info >= (3, 10): __all__ = [ @@ -317,7 +319,7 @@ if sys.version_info < (3, 7): cookie_re: Pattern[str] blank_re: Pattern[bytes] -_Position = tuple[int, int] +_Position: TypeAlias = tuple[int, int] class _TokenInfo(NamedTuple): type: int @@ -331,7 +333,7 @@ class TokenInfo(_TokenInfo): def exact_type(self) -> int: ... # Backwards compatible tokens can be sequences of a shorter length too -_Token = TokenInfo | Sequence[int | str | _Position] +_Token: TypeAlias = TokenInfo | Sequence[int | str | _Position] class TokenError(Exception): ... class StopTokenizing(Exception): ... # undocumented diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index 6128064478bc..3640cb11a878 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -1,15 +1,16 @@ import sys import types from _typeshed import StrPath -from typing import Any, Callable, Mapping, Sequence, TypeVar -from typing_extensions import ParamSpec +from collections.abc import Callable, Mapping, Sequence +from typing import Any, TypeVar +from typing_extensions import ParamSpec, TypeAlias __all__ = ["Trace", "CoverageResults"] _T = TypeVar("_T") _P = ParamSpec("_P") -_localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = tuple[str, str | None, str] +_localtrace: TypeAlias = Callable[[types.FrameType, str, Any], Callable[..., Any]] +_fileModuleFunction: TypeAlias = tuple[str, str | None, str] class CoverageResults: def __init__( diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 859bfef64622..5c4d323a2d9f 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import Self, SupportsWrite +from collections.abc import Generator, Iterable, Iterator, Mapping from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, Mapping, overload -from typing_extensions import Literal +from typing import IO, Any, overload +from typing_extensions import Literal, TypeAlias __all__ = [ "extract_stack", @@ -26,7 +27,7 @@ __all__ = [ "walk_tb", ] -_PT = tuple[str, int, str, str | None] +_PT: TypeAlias = tuple[str, int, str, str | None] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index e2e6800cbab4..193a4acc7c2d 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,7 +1,8 @@ import sys from _tracemalloc import * -from typing import Any, Sequence, Union, overload -from typing_extensions import SupportsIndex +from collections.abc import Sequence +from typing import Any, Union, overload +from typing_extensions import SupportsIndex, TypeAlias def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... @@ -41,7 +42,7 @@ class StatisticDiff: def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... def __eq__(self, other: object) -> bool: ... -_FrameTupleT = tuple[str, int] +_FrameTupleT: TypeAlias = tuple[str, int] class Frame: @property @@ -61,9 +62,9 @@ class Frame: def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... if sys.version_info >= (3, 9): - _TraceTupleT = Union[tuple[int, int, Sequence[_FrameTupleT], int | None], tuple[int, int, Sequence[_FrameTupleT]]] + _TraceTupleT: TypeAlias = Union[tuple[int, int, Sequence[_FrameTupleT], int | None], tuple[int, int, Sequence[_FrameTupleT]]] else: - _TraceTupleT = tuple[int, int, Sequence[_FrameTupleT]] + _TraceTupleT: TypeAlias = tuple[int, int, Sequence[_FrameTupleT]] class Trace: @property diff --git a/mypy/typeshed/stdlib/tty.pyi b/mypy/typeshed/stdlib/tty.pyi index 08c93f6f2e84..8edae9ec2deb 100644 --- a/mypy/typeshed/stdlib/tty.pyi +++ b/mypy/typeshed/stdlib/tty.pyi @@ -1,10 +1,11 @@ import sys from typing import IO +from typing_extensions import TypeAlias if sys.platform != "win32": __all__ = ["setraw", "setcbreak"] - _FD = int | IO[str] + _FD: TypeAlias = int | IO[str] # XXX: Undocumented integer constants IFLAG: int diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index 2ff965465be6..3e91a5eb0ebf 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -1,6 +1,8 @@ from _typeshed import Self +from collections.abc import Callable, Sequence from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar -from typing import Any, Callable, ClassVar, Sequence, Union, overload +from typing import Any, ClassVar, Union, overload +from typing_extensions import TypeAlias __all__ = [ "ScrolledCanvas", @@ -131,18 +133,18 @@ __all__ = [ # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color = Union[str, tuple[float, float, float]] -_AnyColor = Any +_Color: TypeAlias = Union[str, tuple[float, float, float]] +_AnyColor: TypeAlias = Any # TODO: Replace this with a TypedDict once it becomes standardized. -_PenState = dict[str, Any] +_PenState: TypeAlias = dict[str, Any] -_Speed = str | float -_PolygonCoords = Sequence[tuple[float, float]] +_Speed: TypeAlias = str | float +_PolygonCoords: TypeAlias = Sequence[tuple[float, float]] # TODO: Type this more accurately # Vec2D is actually a custom subclass of 'tuple'. -Vec2D = tuple[float, float] +Vec2D: TypeAlias = tuple[float, float] # Does not actually inherit from Canvas, but dynamically gets all methods of Canvas class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 9b2fa1f4a2aa..872ed57a7c76 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -1,26 +1,23 @@ import sys from _typeshed import SupportsKeysAndGetItem -from importlib.abc import _LoaderProtocol -from importlib.machinery import ModuleSpec -from typing import ( - Any, +from collections.abc import ( AsyncGenerator, Awaitable, Callable, - ClassVar, Coroutine, Generator, - Generic, ItemsView, Iterable, Iterator, KeysView, - Mapping, MutableSequence, - TypeVar, ValuesView, - overload, ) +from importlib.abc import _LoaderProtocol +from importlib.machinery import ModuleSpec + +# pytype crashes if types.MappingProxyType inherits from collections.abc.Mapping instead of typing.Mapping +from typing import Any, ClassVar, Generic, Mapping, TypeVar, overload # noqa: Y027 from typing_extensions import Literal, ParamSpec, final if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 4ad3ab3da274..28b588d79c9b 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -22,9 +22,12 @@ if sys.version_info >= (3, 11): "ForwardRef", "Generic", "Literal", + "LiteralString", + "NotRequired", "Optional", "ParamSpec", "Protocol", + "Required", "Tuple", "Type", "TypeVar", @@ -84,9 +87,11 @@ if sys.version_info >= (3, 11): "assert_never", "assert_type", "cast", + "clear_overloads", "final", "get_args", "get_origin", + "get_overloads", "get_type_hints", "is_typeddict", "Never", @@ -528,6 +533,9 @@ if sys.version_info >= (3, 11): Self: _SpecialForm Never: _SpecialForm = ... Unpack: _SpecialForm + Required: _SpecialForm + NotRequired: _SpecialForm + LiteralString: _SpecialForm class TypeVarTuple: __name__: str @@ -1138,7 +1146,7 @@ class Pattern(Generic[AnyStr]): # Functions if sys.version_info >= (3, 7): - _get_type_hints_obj_allowed_types = ( + _get_type_hints_obj_allowed_types = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed object | Callable[..., Any] | FunctionType @@ -1150,7 +1158,9 @@ if sys.version_info >= (3, 7): | MethodDescriptorType ) else: - _get_type_hints_obj_allowed_types = object | Callable[..., Any] | FunctionType | BuiltinFunctionType | MethodType | ModuleType + _get_type_hints_obj_allowed_types = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + object | Callable[..., Any] | FunctionType | BuiltinFunctionType | MethodType | ModuleType + ) if sys.version_info >= (3, 9): def get_type_hints( @@ -1180,6 +1190,8 @@ if sys.version_info >= (3, 11): def reveal_type(__obj: _T) -> _T: ... def assert_never(__arg: Never) -> Never: ... def assert_type(__val: _T, __typ: Any) -> _T: ... + def clear_overloads() -> None: ... + def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... # Type constructors diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 70f395446b0b..1c75ec38e75c 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -22,6 +22,7 @@ from typing import ( # noqa: Y022,Y027 Mapping, NewType as NewType, NoReturn as NoReturn, + Sequence, Text as Text, Type as Type, TypeVar, @@ -76,8 +77,10 @@ __all__ = [ "NoReturn", "Required", "NotRequired", + "clear_overloads", "get_args", "get_origin", + "get_overloads", "get_type_hints", ] @@ -188,10 +191,17 @@ else: # New things in 3.11 if sys.version_info >= (3, 11): from typing import ( + LiteralString as LiteralString, Never as Never, + NotRequired as NotRequired, + Required as Required, Self as Self, + TypeVarTuple as TypeVarTuple, + Unpack as Unpack, assert_never as assert_never, assert_type as assert_type, + clear_overloads as clear_overloads, + get_overloads as get_overloads, reveal_type as reveal_type, ) else: @@ -200,23 +210,26 @@ else: def reveal_type(__obj: _T) -> _T: ... def assert_never(__arg: NoReturn) -> NoReturn: ... def assert_type(__val: _T, __typ: Any) -> _T: ... + def clear_overloads() -> None: ... + def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... -# Experimental (hopefully these will be in 3.11) -Required: _SpecialForm -NotRequired: _SpecialForm -LiteralString: _SpecialForm -Unpack: _SpecialForm + Required: _SpecialForm + NotRequired: _SpecialForm + LiteralString: _SpecialForm + Unpack: _SpecialForm -@final -class TypeVarTuple: - __name__: str - def __init__(self, name: str) -> None: ... - def __iter__(self) -> Any: ... # Unpack[Self] + @final + class TypeVarTuple: + __name__: str + 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_descriptors: tuple[type[Any] | Callable[..., Any], ...] = ..., + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., + **kwargs: object, ) -> Callable[[_T], _T]: ... diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index 0442ec444559..55407ec3f1c8 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -1,4 +1,4 @@ -from typing import Awaitable, Callable +from collections.abc import Awaitable, Callable from typing_extensions import ParamSpec from .case import TestCase diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 87441920fe50..578bd6d6f271 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -3,25 +3,10 @@ import logging import sys import unittest.result from _typeshed import Self -from collections.abc import Set as AbstractSet +from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet from contextlib import AbstractContextManager from types import TracebackType -from typing import ( - Any, - AnyStr, - Callable, - ClassVar, - Container, - Generic, - Iterable, - Mapping, - NamedTuple, - NoReturn, - Pattern, - Sequence, - TypeVar, - overload, -) +from typing import Any, AnyStr, ClassVar, Generic, NamedTuple, NoReturn, Pattern, TypeVar, overload from typing_extensions import ParamSpec from warnings import WarningMessage diff --git a/mypy/typeshed/stdlib/unittest/loader.pyi b/mypy/typeshed/stdlib/unittest/loader.pyi index 8b3c82233cec..76c60f4803f5 100644 --- a/mypy/typeshed/stdlib/unittest/loader.pyi +++ b/mypy/typeshed/stdlib/unittest/loader.pyi @@ -2,11 +2,13 @@ import sys import unittest.case import unittest.result import unittest.suite +from collections.abc import Callable, Sequence from types import ModuleType -from typing import Any, Callable, Pattern, Sequence +from typing import Any, Pattern +from typing_extensions import TypeAlias -_SortComparisonMethod = Callable[[str, str], int] -_SuiteClass = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] +_SortComparisonMethod: TypeAlias = Callable[[str, str], int] +_SuiteClass: TypeAlias = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] VALID_MODULE_NAME: Pattern[str] diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index d3c0ca722f4d..31853676b011 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -3,8 +3,9 @@ import unittest.case import unittest.loader import unittest.result import unittest.suite +from collections.abc import Iterable from types import ModuleType -from typing import Any, Iterable, Protocol +from typing import Any, Protocol MAIN_EXAMPLES: str MODULE_EXAMPLES: str diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index f5cd4218cea0..400bdaac3b41 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import Self +from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from contextlib import _GeneratorContextManager from types import TracebackType -from typing import Any, Awaitable, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload -from typing_extensions import Literal +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Literal, TypeAlias _T = TypeVar("_T") _TT = TypeVar("_TT", bound=type[Any]) @@ -77,9 +78,9 @@ class _Sentinel: sentinel: Any DEFAULT: Any -_ArgsKwargs = tuple[tuple[Any, ...], Mapping[str, Any]] -_NameArgsKwargs = tuple[str, tuple[Any, ...], Mapping[str, Any]] -_CallValue = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs +_ArgsKwargs: TypeAlias = tuple[tuple[Any, ...], Mapping[str, Any]] +_NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]] +_CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs class _Call(tuple[Any, ...]): def __new__( @@ -283,9 +284,9 @@ class _patch_dict: stop: Any if sys.version_info >= (3, 8): - _Mock = MagicMock | AsyncMock + _Mock: TypeAlias = MagicMock | AsyncMock else: - _Mock = MagicMock + _Mock: TypeAlias = MagicMock class _patcher: TEST_PREFIX: str @@ -296,7 +297,7 @@ class _patcher: @overload def __call__( # type: ignore[misc] self, - target: Any, + target: str, new: _T, spec: Any | None = ..., create: bool = ..., @@ -308,7 +309,7 @@ class _patcher: @overload def __call__( self, - target: Any, + target: str, *, spec: Any | None = ..., create: bool = ..., diff --git a/mypy/typeshed/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi index 1c79f8ab648c..5dfec13cb52c 100644 --- a/mypy/typeshed/stdlib/unittest/result.pyi +++ b/mypy/typeshed/stdlib/unittest/result.pyi @@ -1,8 +1,7 @@ import unittest.case -from types import TracebackType -from typing import Any, Callable, TextIO, TypeVar, Union - -_SysExcInfoType = Union[tuple[type[BaseException], BaseException, TracebackType], tuple[None, None, None]] +from _typeshed import OptExcInfo +from collections.abc import Callable +from typing import Any, TextIO, TypeVar _F = TypeVar("_F", bound=Callable[..., Any]) @@ -31,10 +30,10 @@ class TestResult: def stopTest(self, test: unittest.case.TestCase) -> None: ... def startTestRun(self) -> None: ... def stopTestRun(self) -> None: ... - def addError(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... - def addFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... + def addError(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... + def addFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... def addSuccess(self, test: unittest.case.TestCase) -> None: ... def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: ... - def addExpectedFailure(self, test: unittest.case.TestCase, err: _SysExcInfoType) -> None: ... + def addExpectedFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ... - def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: _SysExcInfoType | None) -> None: ... + def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: OptExcInfo | None) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi index 479a9f2c304c..1f1b89bc1bee 100644 --- a/mypy/typeshed/stdlib/unittest/runner.pyi +++ b/mypy/typeshed/stdlib/unittest/runner.pyi @@ -1,9 +1,11 @@ import unittest.case import unittest.result import unittest.suite -from typing import Callable, Iterable, TextIO +from collections.abc import Callable, Iterable +from typing import TextIO +from typing_extensions import TypeAlias -_ResultClassType = Callable[[TextIO, bool, int], unittest.result.TestResult] +_ResultClassType: TypeAlias = Callable[[TextIO, bool, int], unittest.result.TestResult] class TextTestResult(unittest.result.TestResult): descriptions: bool # undocumented diff --git a/mypy/typeshed/stdlib/unittest/signals.pyi b/mypy/typeshed/stdlib/unittest/signals.pyi index e6f5f95e1eb1..89e108d926a6 100644 --- a/mypy/typeshed/stdlib/unittest/signals.pyi +++ b/mypy/typeshed/stdlib/unittest/signals.pyi @@ -1,5 +1,6 @@ import unittest.result -from typing import Callable, TypeVar, overload +from collections.abc import Callable +from typing import TypeVar, overload from typing_extensions import ParamSpec _P = ParamSpec("_P") diff --git a/mypy/typeshed/stdlib/unittest/suite.pyi b/mypy/typeshed/stdlib/unittest/suite.pyi index ca483b06ac9f..26bef658f1cd 100644 --- a/mypy/typeshed/stdlib/unittest/suite.pyi +++ b/mypy/typeshed/stdlib/unittest/suite.pyi @@ -1,8 +1,9 @@ import unittest.case import unittest.result -from typing import Iterable, Iterator +from collections.abc import Iterable, Iterator +from typing_extensions import TypeAlias -_TestType = unittest.case.TestCase | TestSuite +_TestType: TypeAlias = unittest.case.TestCase | TestSuite class BaseTestSuite(Iterable[_TestType]): _tests: list[unittest.case.TestCase] diff --git a/mypy/typeshed/stdlib/unittest/util.pyi b/mypy/typeshed/stdlib/unittest/util.pyi index 30ab6061b100..f62c728760ff 100644 --- a/mypy/typeshed/stdlib/unittest/util.pyi +++ b/mypy/typeshed/stdlib/unittest/util.pyi @@ -1,7 +1,9 @@ -from typing import Any, Sequence, TypeVar +from collections.abc import Sequence +from typing import Any, TypeVar +from typing_extensions import TypeAlias _T = TypeVar("_T") -_Mismatch = tuple[_T, _T, int] +_Mismatch: TypeAlias = tuple[_T, _T, int] _MAX_LENGTH: int _PLACEHOLDER_LEN: int diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index a45e23dd9084..c6a6836e6e95 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,5 +1,7 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, overload +from collections.abc import Callable, Mapping, Sequence +from typing import Any, AnyStr, Generic, NamedTuple, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -28,7 +30,7 @@ __all__ = [ "SplitResultBytes", ] -_Str = bytes | str +_Str: TypeAlias = bytes | str uses_relative: list[str] uses_netloc: list[str] diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 265ef2196715..5e6dde01480a 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -1,10 +1,12 @@ import ssl import sys from _typeshed import StrOrBytesPath, SupportsRead +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from email.message import Message from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol from http.cookiejar import CookieJar -from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, MutableMapping, NoReturn, Pattern, Sequence, TypeVar, overload +from typing import IO, Any, ClassVar, NoReturn, Pattern, TypeVar, overload +from typing_extensions import TypeAlias from urllib.error import HTTPError from urllib.response import addclosehook, addinfourl @@ -46,8 +48,8 @@ __all__ = [ ] _T = TypeVar("_T") -_UrlopenRet = Any -_DataType = bytes | SupportsRead[bytes] | Iterable[bytes] | None +_UrlopenRet: TypeAlias = Any +_DataType: TypeAlias = bytes | SupportsRead[bytes] | Iterable[bytes] | None def urlopen( url: str | Request, diff --git a/mypy/typeshed/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi index 2efec0d47d44..8c9a600f3c48 100644 --- a/mypy/typeshed/stdlib/urllib/response.pyi +++ b/mypy/typeshed/stdlib/urllib/response.pyi @@ -1,8 +1,9 @@ import sys from _typeshed import Self +from collections.abc import Callable, Iterable from email.message import Message from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable +from typing import IO, Any, BinaryIO __all__ = ["addbase", "addclosehook", "addinfo", "addinfourl"] diff --git a/mypy/typeshed/stdlib/urllib/robotparser.pyi b/mypy/typeshed/stdlib/urllib/robotparser.pyi index d1d69546db42..795cf83fcecd 100644 --- a/mypy/typeshed/stdlib/urllib/robotparser.pyi +++ b/mypy/typeshed/stdlib/urllib/robotparser.pyi @@ -1,5 +1,6 @@ import sys -from typing import Iterable, NamedTuple +from collections.abc import Iterable +from typing import NamedTuple __all__ = ["RobotFileParser"] diff --git a/mypy/typeshed/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi index d75df67a1f76..4ebb12be8858 100644 --- a/mypy/typeshed/stdlib/uu.pyi +++ b/mypy/typeshed/stdlib/uu.pyi @@ -1,9 +1,10 @@ import sys from typing import BinaryIO +from typing_extensions import TypeAlias __all__ = ["Error", "encode", "decode"] -_File = str | BinaryIO +_File: TypeAlias = str | BinaryIO class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index 4d46e89beddd..fd7f1334e52a 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -1,9 +1,10 @@ import sys +from typing_extensions import TypeAlias # Because UUID has properties called int and bytes we need to rename these temporarily. -_Int = int -_Bytes = bytes -_FieldsType = tuple[int, int, int, int, int, int] +_Int: TypeAlias = int +_Bytes: TypeAlias = bytes +_FieldsType: TypeAlias = tuple[int, int, int, int, int, int] if sys.version_info >= (3, 7): from enum import Enum diff --git a/mypy/typeshed/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi index 815490a205ab..6afe328ac90d 100644 --- a/mypy/typeshed/stdlib/venv/__init__.pyi +++ b/mypy/typeshed/stdlib/venv/__init__.pyi @@ -1,7 +1,7 @@ +from collections.abc import Sequence import sys from _typeshed import StrOrBytesPath from types import SimpleNamespace -from typing import Sequence if sys.version_info >= (3, 9): CORE_VENV_DEPS: tuple[str, ...] diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index 1799d69f5ba6..bd7afb2d7cba 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,7 +1,8 @@ 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, Sequence, TextIO, overload -from typing_extensions import Literal +from typing import Any, TextIO, overload +from typing_extensions import Literal, TypeAlias __all__ = [ "warn", @@ -14,7 +15,7 @@ __all__ = [ "catch_warnings", ] -_ActionKind = Literal["default", "error", "ignore", "always", "module", "once"] +_ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] filters: Sequence[tuple[str, str | None, type[Warning], str | None, int]] # undocumented, do not mutate diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index de20c6c4f5d4..689282f69ee7 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,14 +1,14 @@ import sys from _typeshed import ReadableBuffer, Self from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, overload -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): __all__ = ["open", "Error", "Wave_read", "Wave_write"] else: __all__ = ["open", "openfp", "Error", "Wave_read", "Wave_write"] -_File = str | IO[bytes] +_File: TypeAlias = str | IO[bytes] class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 820488529143..03dd89c8e210 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Self, SupportsKeysAndGetItem from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, TypeVar, overload +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Generic, TypeVar, overload from typing_extensions import ParamSpec from _weakref import ( diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index ce8fca262d2d..a5b04a262596 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -1,6 +1,6 @@ import sys from abc import abstractmethod -from typing import Callable, Sequence +from collections.abc import Callable, Sequence from typing_extensions import Literal __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index 5dc7e4363d6f..2cc42318f1a4 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -2,10 +2,10 @@ import sys from _typeshed import Self from types import TracebackType from typing import Any -from typing_extensions import Literal, final +from typing_extensions import Literal, TypeAlias, final if sys.platform == "win32": - _KeyType = HKEYType | int + _KeyType: TypeAlias = HKEYType | int def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... diff --git a/mypy/typeshed/stdlib/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/wsgiref/handlers.pyi index 9e2153788cac..655fba668598 100644 --- a/mypy/typeshed/stdlib/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/handlers.pyi @@ -1,15 +1,14 @@ +from _typeshed import OptExcInfo +from _typeshed.wsgi import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from abc import abstractmethod -from types import TracebackType -from typing import IO, Callable, MutableMapping +from collections.abc import Callable, MutableMapping +from typing import IO from .headers import Headers -from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper __all__ = ["BaseHandler", "SimpleHandler", "BaseCGIHandler", "CGIHandler", "IISCGIHandler", "read_environ"] -_exc_info = tuple[type[BaseException] | None, BaseException | None, TracebackType | None] - def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: ... @@ -39,7 +38,7 @@ class BaseHandler: def set_content_length(self) -> None: ... def cleanup_headers(self) -> None: ... def start_response( - self, status: str, headers: list[tuple[str, str]], exc_info: _exc_info | None = ... + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ... ) -> Callable[[bytes], None]: ... def send_preamble(self) -> None: ... def write(self, data: bytes) -> None: ... @@ -49,7 +48,7 @@ class BaseHandler: def send_headers(self) -> None: ... def result_is_file(self) -> bool: ... def client_is_modern(self) -> bool: ... - def log_exception(self, exc_info: _exc_info) -> None: ... + def log_exception(self, exc_info: OptExcInfo) -> None: ... def handle_error(self) -> None: ... def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/wsgiref/headers.pyi b/mypy/typeshed/stdlib/wsgiref/headers.pyi index b62124a2a936..cde0227a7830 100644 --- a/mypy/typeshed/stdlib/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/headers.pyi @@ -1,6 +1,7 @@ from typing import Pattern, overload +from typing_extensions import TypeAlias -_HeaderList = list[tuple[str, str]] +_HeaderList: TypeAlias = list[tuple[str, str]] tspecials: Pattern[str] # undocumented diff --git a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi index 389d30c22db2..1dc84e9fbebe 100644 --- a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi @@ -1,8 +1,8 @@ +from _typeshed.wsgi import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment from http.server import BaseHTTPRequestHandler, HTTPServer from typing import TypeVar, overload from .handlers import SimpleHandler -from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment __all__ = ["WSGIServer", "WSGIRequestHandler", "demo_app", "make_server"] diff --git a/mypy/typeshed/stdlib/wsgiref/types.pyi b/mypy/typeshed/stdlib/wsgiref/types.pyi index c272ae67c391..b8ece8d57a9d 100644 --- a/mypy/typeshed/stdlib/wsgiref/types.pyi +++ b/mypy/typeshed/stdlib/wsgiref/types.pyi @@ -1,3 +1,32 @@ -# Obsolete, use _typeshed.wsgi directly. +from collections.abc import Callable, Iterable +from sys import _OptExcInfo +from typing import Any, Protocol +from typing_extensions import TypeAlias -from _typeshed.wsgi import * +__all__ = ["StartResponse", "WSGIEnvironment", "WSGIApplication", "InputStream", "ErrorStream", "FileWrapper"] + +class StartResponse(Protocol): + def __call__( + self, __status: str, __headers: list[tuple[str, str]], __exc_info: _OptExcInfo | None = ... + ) -> Callable[[bytes], object]: ... + +WSGIEnvironment: TypeAlias = dict[str, Any] +WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] + +class InputStream(Protocol): + def read(self, __size: int = ...) -> bytes: ... + def readline(self, __size: int = ...) -> bytes: ... + def readlines(self, __hint: int = ...) -> list[bytes]: ... + def __iter__(self) -> Iterable[bytes]: ... + +class ErrorStream(Protocol): + def flush(self) -> object: ... + def write(self, __s: str) -> object: ... + def writelines(self, __seq: list[str]) -> object: ... + +class _Readable(Protocol): + def read(self, __size: int = ...) -> bytes: ... + # Optional: def close(self) -> object: ... + +class FileWrapper(Protocol): + def __call__(self, __file: _Readable, __block_size: int = ...) -> Iterable[bytes]: ... diff --git a/mypy/typeshed/stdlib/wsgiref/util.pyi b/mypy/typeshed/stdlib/wsgiref/util.pyi index f2c3135df786..36e5c1e69676 100644 --- a/mypy/typeshed/stdlib/wsgiref/util.pyi +++ b/mypy/typeshed/stdlib/wsgiref/util.pyi @@ -1,7 +1,7 @@ import sys -from typing import IO, Any, Callable - -from .types import WSGIEnvironment +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Callable +from typing import IO, Any __all__ = ["FileWrapper", "guess_scheme", "application_uri", "request_uri", "shift_path_info", "setup_testing_defaults"] diff --git a/mypy/typeshed/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi index 35491756c288..ada2283a6af0 100644 --- a/mypy/typeshed/stdlib/wsgiref/validate.pyi +++ b/mypy/typeshed/stdlib/wsgiref/validate.pyi @@ -1,5 +1,6 @@ from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication -from typing import Any, Callable, Iterable, Iterator, NoReturn +from collections.abc import Callable, Iterable, Iterator +from typing import Any, NoReturn __all__ = ["validator"] diff --git a/mypy/typeshed/stdlib/xdrlib.pyi b/mypy/typeshed/stdlib/xdrlib.pyi index e9716e29014d..e6b78d5542be 100644 --- a/mypy/typeshed/stdlib/xdrlib.pyi +++ b/mypy/typeshed/stdlib/xdrlib.pyi @@ -1,4 +1,5 @@ -from typing import Callable, Sequence, TypeVar +from collections.abc import Callable, Sequence +from typing import TypeVar __all__ = ["Error", "Packer", "Unpacker", "ConversionError"] diff --git a/mypy/typeshed/stdlib/xml/dom/domreg.pyi b/mypy/typeshed/stdlib/xml/dom/domreg.pyi index b9e2dd9eb263..5a276ae5f561 100644 --- a/mypy/typeshed/stdlib/xml/dom/domreg.pyi +++ b/mypy/typeshed/stdlib/xml/dom/domreg.pyi @@ -1,5 +1,5 @@ from _typeshed.xml import DOMImplementation -from typing import Callable, Iterable +from collections.abc import Callable, Iterable well_known_implementations: dict[str, str] registered: dict[str, Callable[[], DOMImplementation]] diff --git a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi index 411401d11ccd..4507b3d98ee7 100644 --- a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi @@ -1,4 +1,5 @@ -from typing import Any, Iterable, TypeVar +from collections.abc import Iterable +from typing import Any, TypeVar __all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] diff --git a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi index b2bec64fd1dc..07f220ddd347 100644 --- a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import SupportsRead -from typing import Any, Sequence -from typing_extensions import Literal +from collections.abc import Sequence +from typing import Any +from typing_extensions import Literal, TypeAlias from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler from xml.sax.xmlreader import XMLReader @@ -15,10 +16,10 @@ PROCESSING_INSTRUCTION: Literal["PROCESSING_INSTRUCTION"] IGNORABLE_WHITESPACE: Literal["IGNORABLE_WHITESPACE"] CHARACTERS: Literal["CHARACTERS"] -_DocumentFactory = DOMImplementation | None -_Node = Document | Element | Text +_DocumentFactory: TypeAlias = DOMImplementation | None +_Node: TypeAlias = Document | Element | Text -_Event = tuple[ +_Event: TypeAlias = tuple[ Literal[ Literal["START_ELEMENT"], Literal["END_ELEMENT"], diff --git a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi index ec47ec134e08..f6afd8aa2786 100644 --- a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -1,5 +1,5 @@ from typing import Any, NoReturn -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from urllib.request import OpenerDirector from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS from xml.dom.minidom import Node @@ -18,13 +18,13 @@ __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] # probably the same as `Options.errorHandler`? # Maybe `xml.sax.handler.ErrorHandler`? -_DOMBuilderErrorHandlerType = Any | None +_DOMBuilderErrorHandlerType: TypeAlias = Any | None # probably some kind of IO... -_DOMInputSourceCharacterStreamType = Any | None +_DOMInputSourceCharacterStreamType: TypeAlias = Any | None # probably a string?? -_DOMInputSourceStringDataType = Any | None +_DOMInputSourceStringDataType: TypeAlias = Any | None # probably a string?? -_DOMInputSourceEncodingType = Any | None +_DOMInputSourceEncodingType: TypeAlias = Any | None class Options: namespaces: int diff --git a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi index 5cd85cc21753..7bb78d0628ce 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi @@ -1,5 +1,5 @@ import sys -from typing import Callable +from collections.abc import Callable from xml.etree.ElementTree import Element XINCLUDE: str diff --git a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi index 5a2dd69c1bee..e5b8223aab34 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi @@ -1,11 +1,13 @@ -from typing import Callable, Generator, Pattern, TypeVar +from collections.abc import Callable, Generator +from typing import Pattern, TypeVar +from typing_extensions import TypeAlias from xml.etree.ElementTree import Element xpath_tokenizer_re: Pattern[str] -_token = tuple[str, str] -_next = Callable[[], _token] -_callback = Callable[[_SelectorContext, list[Element]], Generator[Element, None, None]] +_token: TypeAlias = tuple[str, str] +_next: TypeAlias = Callable[[], _token] +_callback: TypeAlias = Callable[[_SelectorContext, list[Element]], Generator[Element, None, None]] def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = ...) -> Generator[_token, None, None]: ... def get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 7b50b4279021..414530b0a34c 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -1,20 +1,8 @@ import sys from _typeshed import FileDescriptor, StrOrBytesPath, SupportsRead, SupportsWrite -from typing import ( - Any, - Callable, - Generator, - ItemsView, - Iterable, - Iterator, - KeysView, - Mapping, - MutableSequence, - Sequence, - TypeVar, - overload, -) -from typing_extensions import Literal, SupportsIndex, TypeGuard +from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, KeysView, Mapping, MutableSequence, Sequence +from typing import Any, TypeVar, overload +from typing_extensions import Literal, SupportsIndex, TypeAlias, TypeGuard if sys.version_info >= (3, 9): __all__ = [ @@ -101,9 +89,9 @@ else: ] _T = TypeVar("_T") -_FileRead = StrOrBytesPath | FileDescriptor | SupportsRead[bytes] | SupportsRead[str] -_FileWriteC14N = StrOrBytesPath | FileDescriptor | SupportsWrite[bytes] -_FileWrite = _FileWriteC14N | SupportsWrite[str] +_FileRead: TypeAlias = StrOrBytesPath | FileDescriptor | SupportsRead[bytes] | SupportsRead[str] +_FileWriteC14N: TypeAlias = StrOrBytesPath | FileDescriptor | SupportsWrite[bytes] +_FileWrite: TypeAlias = _FileWriteC14N | SupportsWrite[str] VERSION: str @@ -352,7 +340,7 @@ def fromstringlist(sequence: Sequence[str | bytes], parser: XMLParser | None = . # TreeBuilder is called by client code (they could pass strs, bytes or whatever); # but we don't want to use a too-broad type, or it would be too hard to write # elementfactories. -_ElementFactory = Callable[[Any, dict[Any, Any]], Element] +_ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element] class TreeBuilder: if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi index 418164aa887f..22a2764a699f 100644 --- a/mypy/typeshed/stdlib/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/sax/__init__.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import SupportsRead, _T_co -from typing import Any, Iterable, NoReturn, Protocol +from collections.abc import Iterable +from typing import Any, NoReturn, Protocol from xml.sax.handler import ContentHandler, ErrorHandler from xml.sax.xmlreader import Locator, XMLReader diff --git a/mypy/typeshed/stdlib/xml/sax/saxutils.pyi b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi index c7304f4b5261..1361949d0c3e 100644 --- a/mypy/typeshed/stdlib/xml/sax/saxutils.pyi +++ b/mypy/typeshed/stdlib/xml/sax/saxutils.pyi @@ -1,7 +1,7 @@ from _typeshed import SupportsWrite from codecs import StreamReaderWriter, StreamWriter +from collections.abc import Mapping from io import RawIOBase, TextIOBase -from typing import Mapping from xml.sax import handler, xmlreader def escape(data: str, entities: Mapping[str, str] = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi index 684e9cef1f42..d7d4db5b0a16 100644 --- a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi +++ b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi @@ -1,4 +1,4 @@ -from typing import Mapping +from collections.abc import Mapping class XMLReader: def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index a59be37f9e81..d4e82d5e40da 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -3,21 +3,22 @@ import http.client import sys import time from _typeshed import Self, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Mapping from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, Callable, Iterable, Mapping, Protocol, Union, overload -from typing_extensions import Literal +from typing import Any, Protocol, Union, overload +from typing_extensions import Literal, TypeAlias class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... -_DateTimeComparable = DateTime | datetime | str | _SupportsTimeTuple -_Marshallable = ( +_DateTimeComparable: TypeAlias = DateTime | datetime | str | _SupportsTimeTuple +_Marshallable: TypeAlias = ( bool | int | float | str | bytes | None | tuple[Any, ...] | list[Any] | dict[Any, Any] | datetime | DateTime | Binary ) -_XMLDate = int | datetime | tuple[int, ...] | time.struct_time -_HostType = Union[tuple[str, dict[str, str]], str] +_XMLDate: TypeAlias = int | datetime | tuple[int, ...] | time.struct_time +_HostType: TypeAlias = Union[tuple[str, dict[str, str]], str] def escape(s: str) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 2ed0b03c7151..371f1821b29d 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -2,12 +2,14 @@ import http.server import pydoc import socketserver import sys +from collections.abc import Callable, Iterable, Mapping from datetime import datetime -from typing import Any, Callable, Iterable, Mapping, Pattern, Protocol +from typing import Any, Pattern, Protocol +from typing_extensions import TypeAlias from xmlrpc.client import Fault # TODO: Recursive type on tuple, list, dict -_Marshallable = None | bool | int | float | str | bytes | tuple[Any, ...] | list[Any] | dict[Any, Any] | datetime +_Marshallable: TypeAlias = None | bool | int | float | str | bytes | tuple[Any, ...] | list[Any] | dict[Any, Any] | datetime # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy class _DispatchArity0(Protocol): @@ -30,7 +32,9 @@ class _DispatchArity4(Protocol): class _DispatchArityN(Protocol): def __call__(self, *args: _Marshallable) -> _Marshallable: ... -_DispatchProtocol = _DispatchArity0 | _DispatchArity1 | _DispatchArity2 | _DispatchArity3 | _DispatchArity4 | _DispatchArityN +_DispatchProtocol: TypeAlias = ( + _DispatchArity0 | _DispatchArity1 | _DispatchArity2 | _DispatchArity3 | _DispatchArity4 | _DispatchArityN +) def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = ...) -> Any: ... # undocumented def list_public_methods(obj: Any) -> list[str]: ... # undocumented diff --git a/mypy/typeshed/stdlib/zipapp.pyi b/mypy/typeshed/stdlib/zipapp.pyi index c3cf8321dbc4..d42640141620 100644 --- a/mypy/typeshed/stdlib/zipapp.pyi +++ b/mypy/typeshed/stdlib/zipapp.pyi @@ -1,10 +1,12 @@ import sys +from collections.abc import Callable from pathlib import Path -from typing import BinaryIO, Callable +from typing import BinaryIO +from typing_extensions import TypeAlias __all__ = ["ZipAppError", "create_archive", "get_interpreter"] -_Path = str | Path | BinaryIO +_Path: TypeAlias = str | Path | BinaryIO class ZipAppError(ValueError): ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index b837528d7dfa..d5255b15c3c0 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -1,10 +1,11 @@ import io import sys from _typeshed import Self, StrOrBytesPath, StrPath +from collections.abc import Callable, Iterable, Iterator, Sequence from os import PathLike from types import TracebackType -from typing import IO, Any, Callable, Iterable, Iterator, Protocol, Sequence, overload -from typing_extensions import Literal +from typing import IO, Any, Protocol, overload +from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 8): __all__ = [ @@ -38,10 +39,10 @@ else: "LargeZipFile", ] -_DateTuple = tuple[int, int, int, int, int, int] -_ReadWriteMode = Literal["r", "w"] -_ReadWriteBinaryMode = Literal["r", "w", "rb", "wb"] -_ZipFileMode = Literal["r", "w", "x", "a"] +_DateTuple: TypeAlias = tuple[int, int, int, int, int, int] +_ReadWriteMode: TypeAlias = Literal["r", "w"] +_ReadWriteBinaryMode: TypeAlias = Literal["r", "w", "rb", "wb"] +_ZipFileMode: TypeAlias = Literal["r", "w", "x", "a"] class BadZipFile(Exception): ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index d766eab6b7ef..0e898cb29740 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,6 +1,7 @@ from _typeshed import Self, StrPath +from collections.abc import Iterable, Sequence from datetime import tzinfo -from typing import Any, Iterable, Protocol, Sequence +from typing import Any, Protocol __all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] diff --git a/test-data/unit/plugins/decimal_to_int.py b/test-data/unit/plugins/decimal_to_int.py index 21fd3b518b7d..597010f9a6d1 100644 --- a/test-data/unit/plugins/decimal_to_int.py +++ b/test-data/unit/plugins/decimal_to_int.py @@ -4,7 +4,7 @@ class MyPlugin(Plugin): def get_type_analyze_hook(self, fullname): - if fullname == "decimal.Decimal": + if fullname in ("decimal.Decimal", "_decimal.Decimal"): return decimal_to_int_hook return None