diff --git a/stdlib/_typeshed/__init__.pyi b/stdlib/_typeshed/__init__.pyi index fdc889c6b23c..b076c1f6cbbe 100644 --- a/stdlib/_typeshed/__init__.pyi +++ b/stdlib/_typeshed/__init__.pyi @@ -215,4 +215,4 @@ class structseq(Generic[_T_co]): # The second parameter will accept a dict of any kind without raising an exception, # but only has any meaning if you supply it a dict where the keys are strings. # https://github.com/python/typeshed/pull/6560#discussion_r767149830 - def __new__(cls: type[_T], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _T: ... + def __new__(cls: type[Self], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> Self: ... diff --git a/stdlib/_weakrefset.pyi b/stdlib/_weakrefset.pyi index 1f0132f4c240..c738fa8df654 100644 --- a/stdlib/_weakrefset.pyi +++ b/stdlib/_weakrefset.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar if sys.version_info >= (3, 9): @@ -6,14 +7,13 @@ if sys.version_info >= (3, 9): _S = TypeVar("_S") _T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) class WeakSet(MutableSet[_T], Generic[_T]): def __init__(self, data: Iterable[_T] | None = ...) -> None: ... def add(self, item: _T) -> None: ... def clear(self) -> None: ... def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... + def copy(self: Self) -> Self: ... def pop(self) -> _T: ... def remove(self, item: _T) -> None: ... def update(self, other: Iterable[_T]) -> None: ... @@ -21,14 +21,14 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __ior__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def difference(self: Self, other: Iterable[_T]) -> Self: ... + def __sub__(self: Self, other: Iterable[_T]) -> Self: ... def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __isub__(self: Self, other: Iterable[_T]) -> Self: ... + def intersection(self: Self, other: Iterable[_T]) -> Self: ... + def __and__(self: Self, other: Iterable[_T]) -> Self: ... def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __iand__(self: Self, other: Iterable[_T]) -> Self: ... def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi index b4ca53dd9f8c..1d6446b59070 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -69,8 +69,6 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") _R = TypeVar("_R") # Return-type TypeVar _SupportsNextT = TypeVar("_SupportsNextT", bound=SupportsNext[Any], covariant=True) _SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant=True) @@ -87,12 +85,12 @@ class object: __module__: str __annotations__: dict[str, Any] @property - def __class__(self: _T) -> type[_T]: ... + def __class__(self: Self) -> type[Self]: ... # Ignore errors about type mismatch between property getter and setter @__class__.setter def __class__(self, __type: type[object]) -> None: ... # type: ignore # noqa: F811 def __init__(self) -> None: ... - def __new__(cls: type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... def __setattr__(self, __name: str, __value: Any) -> None: ... def __eq__(self, __o: object) -> bool: ... def __ne__(self, __o: object) -> bool: ... @@ -117,7 +115,7 @@ class staticmethod(Generic[_R]): # Special, only valid as a decorator. __func__: Callable[..., _R] __isabstractmethod__: bool def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ... - def __new__(cls: type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R]: ... if sys.version_info >= (3, 10): __name__: str @@ -129,7 +127,7 @@ class classmethod(Generic[_R]): # Special, only valid as a decorator. __func__: Callable[..., _R] __isabstractmethod__: bool def __init__(self: classmethod[_R], __f: Callable[..., _R]) -> None: ... - def __new__(cls: type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R]: ... if sys.version_info >= (3, 10): __name__: str @@ -157,9 +155,9 @@ class type: @overload def __new__(cls, __o: object) -> type: ... @overload - def __new__(cls: type[_TT], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> _TT: ... + def __new__(cls: type[Self], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> Self: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> list[_TT]: ... + def __subclasses__(self: Self) -> list[Self]: ... # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> list[type]: ... @@ -184,9 +182,9 @@ _NegativeInteger = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -1 class int: @overload - def __new__(cls: type[_T], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: type[_T], __x: str | bytes | bytearray, base: SupportsIndex) -> _T: ... + def __new__(cls: type[Self], __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property @@ -269,7 +267,7 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: type[_T], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> _T: ... + def __new__(cls: type[Self], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @@ -326,9 +324,9 @@ class float: class complex: @overload - def __new__(cls: type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: type[_T], real: str | SupportsComplex | SupportsIndex | complex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | SupportsIndex | complex) -> Self: ... @property def real(self) -> float: ... @property @@ -359,9 +357,9 @@ class _FormatMapMapping(Protocol): class str(Sequence[str]): @overload - def __new__(cls: type[_T], object: object = ...) -> _T: ... + def __new__(cls: type[Self], object: object = ...) -> Self: ... @overload - def __new__(cls: type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... + def __new__(cls: type[Self], o: bytes, encoding: str = ..., errors: str = ...) -> Self: ... def capitalize(self) -> str: ... def casefold(self) -> str: ... def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... @@ -443,15 +441,15 @@ class str(Sequence[str]): class bytes(ByteString): @overload - def __new__(cls: type[_T], __ints: Iterable[SupportsIndex]) -> _T: ... + def __new__(cls: type[Self], __ints: Iterable[SupportsIndex]) -> Self: ... @overload - def __new__(cls: type[_T], __string: str, encoding: str, errors: str = ...) -> _T: ... + def __new__(cls: type[Self], __string: str, encoding: str, errors: str = ...) -> Self: ... @overload - def __new__(cls: type[_T], __length: SupportsIndex) -> _T: ... + def __new__(cls: type[Self], __length: SupportsIndex) -> Self: ... @overload - def __new__(cls: type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... @overload - def __new__(cls: type[_T], __o: SupportsBytes) -> _T: ... + def __new__(cls: type[Self], __o: SupportsBytes) -> Self: ... def capitalize(self) -> bytes: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def count( @@ -705,7 +703,7 @@ class memoryview(Sized, Sequence[int]): @final class bool(int): - def __new__(cls: type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... @overload def __and__(self, __x: bool) -> bool: ... @overload @@ -748,7 +746,7 @@ class slice: def indices(self, __len: SupportsIndex) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: type[_T], __iterable: Iterable[_T_co] = ...) -> _T: ... + def __new__(cls: type[Self], __iterable: Iterable[_T_co] = ...) -> Self: ... def __len__(self) -> int: ... def __contains__(self, __x: object) -> bool: ... @overload @@ -820,10 +818,10 @@ class list(MutableSequence[_T], Generic[_T]): def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... def __delitem__(self, __i: SupportsIndex | slice) -> None: ... def __add__(self, __x: list[_T]) -> list[_T]: ... - def __iadd__(self: _S, __x: Iterable[_T]) -> _S: ... + def __iadd__(self: Self, __x: Iterable[_T]) -> Self: ... def __mul__(self, __n: SupportsIndex) -> list[_T]: ... def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... - def __imul__(self: _S, __n: SupportsIndex) -> _S: ... + def __imul__(self: Self, __n: SupportsIndex) -> Self: ... def __contains__(self, __o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... def __gt__(self, __x: list[_T]) -> bool: ... @@ -847,7 +845,7 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ... - def __new__(cls: type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: ... def keys(self) -> dict_keys[_KT, _VT]: ... def values(self) -> dict_values[_KT, _VT]: ... @@ -1523,7 +1521,7 @@ class BaseException: if sys.version_info >= (3, 11): __note__: str | None def __init__(self, *args: object) -> None: ... - def with_traceback(self: _TBE, __tb: TracebackType | None) -> _TBE: ... + def with_traceback(self: Self, __tb: TracebackType | None) -> Self: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... diff --git a/stdlib/cgi.pyi b/stdlib/cgi.pyi index 8eee5c69504d..c78228c09ceb 100644 --- a/stdlib/cgi.pyi +++ b/stdlib/cgi.pyi @@ -1,10 +1,8 @@ import sys -from _typeshed import SupportsGetItem, SupportsItemAccess +from _typeshed import Self, SupportsGetItem, SupportsItemAccess from builtins import type as _type from collections.abc import Iterable, Iterator, Mapping -from typing import IO, Any, Protocol, TypeVar - -_T = TypeVar("_T", bound=FieldStorage) +from typing import IO, Any, Protocol def parse( fp: IO[Any] | None = ..., @@ -93,7 +91,7 @@ class FieldStorage: max_num_fields: int | None = ..., separator: str = ..., ) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: ... diff --git a/stdlib/codecs.pyi b/stdlib/codecs.pyi index 24e04ef7fc91..41f6eae50ebc 100644 --- a/stdlib/codecs.pyi +++ b/stdlib/codecs.pyi @@ -2,7 +2,7 @@ import sys import types from _typeshed import Self from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, TypeVar, overload +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, overload from typing_extensions import Literal BOM32_BE: Literal[b"\xfe\xff"] @@ -201,8 +201,6 @@ class StreamReader(Codec): def __iter__(self) -> Iterator[str]: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_T = TypeVar("_T", bound=StreamReaderWriter) - # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): @@ -211,7 +209,7 @@ class StreamReaderWriter(TextIO): def readline(self, size: int | None = ...) -> str: ... def readlines(self, sizehint: int | None = ...) -> list[str]: ... def __next__(self) -> str: ... - def __iter__(self: _T) -> _T: ... + def __iter__(self: Self) -> Self: ... # This actually returns None, but that's incompatible with the supertype def write(self, data: str) -> int: ... def writelines(self, list: Iterable[str]) -> None: ... @@ -233,8 +231,6 @@ class StreamReaderWriter(TextIO): def tell(self) -> int: ... def writable(self) -> bool: ... -_SRT = TypeVar("_SRT", bound=StreamRecoder) - class StreamRecoder(BinaryIO): def __init__( self, @@ -249,7 +245,7 @@ class StreamRecoder(BinaryIO): def readline(self, size: int | None = ...) -> bytes: ... def readlines(self, sizehint: int | None = ...) -> list[bytes]: ... def __next__(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... + def __iter__(self: Self) -> Self: ... def write(self, data: bytes) -> int: ... def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None def reset(self) -> None: ... diff --git a/stdlib/collections/__init__.pyi b/stdlib/collections/__init__.pyi index c1a046949f83..f1e14a4ce10b 100644 --- a/stdlib/collections/__init__.pyi +++ b/stdlib/collections/__init__.pyi @@ -83,15 +83,15 @@ class UserList(MutableSequence[_T]): @overload def __setitem__(self, i: slice, o: Iterable[_T]) -> None: ... def __delitem__(self, i: SupportsIndex | slice) -> None: ... - def __add__(self: _S, other: Iterable[_T]) -> _S: ... - def __iadd__(self: _S, other: Iterable[_T]) -> _S: ... - def __mul__(self: _S, n: int) -> _S: ... - def __imul__(self: _S, n: int) -> _S: ... + def __add__(self: Self, other: Iterable[_T]) -> Self: ... + def __iadd__(self: Self, other: Iterable[_T]) -> Self: ... + def __mul__(self: Self, n: int) -> Self: ... + def __imul__(self: Self, n: int) -> Self: ... def append(self, item: _T) -> None: ... def insert(self, i: int, item: _T) -> None: ... def pop(self, i: int = ...) -> _T: ... def remove(self, item: _T) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def count(self, item: _T) -> int: ... # All arguments are passed to `list.index` at runtime, so the signature should be kept in line with `list.index`. def index(self, item: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... @@ -118,22 +118,22 @@ class UserString(Sequence[str]): def __contains__(self, char: object) -> bool: ... def __len__(self) -> int: ... # It should return a str to implement Sequence correctly, but it doesn't. - def __getitem__(self: _UserStringT, i: SupportsIndex | slice) -> _UserStringT: ... # type: ignore[override] + def __getitem__(self: Self, i: SupportsIndex | slice) -> Self: ... # type: ignore[override] def __iter__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] def __reversed__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] - def __add__(self: _UserStringT, other: object) -> _UserStringT: ... - def __mul__(self: _UserStringT, n: int) -> _UserStringT: ... - def __mod__(self: _UserStringT, args: Any) -> _UserStringT: ... - def capitalize(self: _UserStringT) -> _UserStringT: ... - def casefold(self: _UserStringT) -> _UserStringT: ... - def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def __add__(self: Self, other: object) -> Self: ... + def __mul__(self: Self, n: int) -> Self: ... + def __mod__(self: Self, args: Any) -> Self: ... + def capitalize(self: Self) -> Self: ... + def casefold(self: Self) -> Self: ... + def center(self: Self, width: int, *args: Any) -> Self: ... def count(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... if sys.version_info >= (3, 8): def encode(self: UserString, encoding: str | None = ..., errors: str | None = ...) -> bytes: ... else: - def encode(self: _UserStringT, encoding: str | None = ..., errors: str | None = ...) -> _UserStringT: ... + def encode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... def endswith(self, suffix: str | tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... + def expandtabs(self: Self, tabsize: int = ...) -> Self: ... def find(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... def format(self, *args: Any, **kwds: Any) -> str: ... def format_map(self, mapping: Mapping[str, Any]) -> str: ... @@ -152,9 +152,9 @@ class UserString(Sequence[str]): if sys.version_info >= (3, 7): def isascii(self) -> bool: ... def join(self, seq: Iterable[str]) -> str: ... - def ljust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... - def lower(self: _UserStringT) -> _UserStringT: ... - def lstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... + def ljust(self: Self, width: int, *args: Any) -> Self: ... + def lower(self: Self) -> Self: ... + def lstrip(self: Self, chars: str | None = ...) -> Self: ... @staticmethod @overload def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... @@ -163,24 +163,24 @@ class UserString(Sequence[str]): def maketrans(x: str, y: str, z: str = ...) -> dict[int, int | None]: ... def partition(self, sep: str) -> tuple[str, str, str]: ... if sys.version_info >= (3, 9): - def removeprefix(self: _UserStringT, __prefix: str | UserString) -> _UserStringT: ... - def removesuffix(self: _UserStringT, __suffix: str | UserString) -> _UserStringT: ... - def replace(self: _UserStringT, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> _UserStringT: ... + def removeprefix(self: Self, __prefix: str | UserString) -> Self: ... + def removesuffix(self: Self, __suffix: str | UserString) -> Self: ... + def replace(self: Self, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> Self: ... def rfind(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def rjust(self: Self, width: int, *args: Any) -> Self: ... def rpartition(self, sep: str) -> tuple[str, str, str]: ... - def rstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... + def rstrip(self: Self, chars: str | None = ...) -> Self: ... def split(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... def splitlines(self, keepends: bool = ...) -> list[str]: ... def startswith(self, prefix: str | tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... - def swapcase(self: _UserStringT) -> _UserStringT: ... - def title(self: _UserStringT) -> _UserStringT: ... - def translate(self: _UserStringT, *args: Any) -> _UserStringT: ... - def upper(self: _UserStringT) -> _UserStringT: ... - def zfill(self: _UserStringT, width: int) -> _UserStringT: ... + def strip(self: Self, chars: str | None = ...) -> Self: ... + def swapcase(self: Self) -> Self: ... + def title(self: Self) -> Self: ... + def translate(self: Self, *args: Any) -> Self: ... + def upper(self: Self) -> Self: ... + def zfill(self: Self, width: int) -> Self: ... class deque(MutableSequence[_T], Generic[_T]): @property @@ -188,7 +188,7 @@ class deque(MutableSequence[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ..., maxlen: int | None = ...) -> None: ... def append(self, __x: _T) -> None: ... def appendleft(self, __x: _T) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def count(self, __x: _T) -> int: ... def extend(self, __iterable: Iterable[_T]) -> None: ... def extendleft(self, __iterable: Iterable[_T]) -> None: ... @@ -198,7 +198,7 @@ class deque(MutableSequence[_T], Generic[_T]): def popleft(self) -> _T: ... def remove(self, __value: _T) -> None: ... def rotate(self, __n: int = ...) -> None: ... - def __copy__(self: _S) -> _S: ... + def __copy__(self: Self) -> Self: ... def __len__(self) -> int: ... # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores def __getitem__(self, __index: SupportsIndex) -> _T: ... # type: ignore[override] @@ -206,10 +206,10 @@ class deque(MutableSequence[_T], Generic[_T]): def __delitem__(self, __i: SupportsIndex) -> None: ... # type: ignore[override] def __contains__(self, __o: object) -> bool: ... def __reduce__(self: Self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... - def __iadd__(self: _S, __iterable: Iterable[_T]) -> _S: ... - def __add__(self: _S, __other: _S) -> _S: ... - def __mul__(self: _S, __other: int) -> _S: ... - def __imul__(self: _S, __other: int) -> _S: ... + def __iadd__(self: Self, __iterable: Iterable[_T]) -> Self: ... + def __add__(self: Self, __other: Self) -> Self: ... + def __mul__(self: Self, __other: int) -> Self: ... + def __imul__(self: Self, __other: int) -> Self: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @@ -306,8 +306,8 @@ class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT ) -> None: ... def __missing__(self, __key: _KT) -> _VT: ... - def __copy__(self: _S) -> _S: ... - def copy(self: _S) -> _S: ... + def __copy__(self: Self) -> Self: ... + def copy(self: Self) -> Self: ... class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] diff --git a/stdlib/ctypes/__init__.pyi b/stdlib/ctypes/__init__.pyi index 8af6f14482da..00e1e25cf0b7 100644 --- a/stdlib/ctypes/__init__.pyi +++ b/stdlib/ctypes/__init__.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import ReadableBuffer, WriteableBuffer +from _typeshed import ReadableBuffer, Self, WriteableBuffer from abc import abstractmethod from typing import ( Any, @@ -83,15 +83,15 @@ class _CData(metaclass=_CDataMeta): _b_needsfree_: bool _objects: Mapping[Any, int] | None @classmethod - def from_buffer(cls: type[_CT], source: WriteableBuffer, offset: int = ...) -> _CT: ... + def from_buffer(cls: type[Self], source: WriteableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_buffer_copy(cls: type[_CT], source: ReadableBuffer, offset: int = ...) -> _CT: ... + def from_buffer_copy(cls: type[Self], source: ReadableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_address(cls: type[_CT], address: int) -> _CT: ... + def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: type[_CT], obj: Any) -> _CT | _CArgObject: ... + def from_param(cls: type[Self], obj: Any) -> Self | _CArgObject: ... @classmethod - def in_dll(cls: type[_CT], library: CDLL, name: str) -> _CT: ... + def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... diff --git a/stdlib/datetime.pyi b/stdlib/datetime.pyi index 6400fb0e6fd6..c5574825e054 100644 --- a/stdlib/datetime.pyi +++ b/stdlib/datetime.pyi @@ -1,9 +1,9 @@ import sys +from _typeshed import Self from time import struct_time from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, TypeVar, overload from typing_extensions import final -_S = TypeVar("_S") _D = TypeVar("_D", bound=date) MINYEAR: int @@ -36,19 +36,19 @@ class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] - def __new__(cls: type[_S], year: int, month: int, day: int) -> _S: ... + def __new__(cls: type[Self], year: int, month: int, day: int) -> Self: ... @classmethod - def fromtimestamp(cls: type[_S], __timestamp: float) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float) -> Self: ... @classmethod - def today(cls: type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: type[_S], __n: int) -> _S: ... + def fromordinal(cls: type[Self], __n: int) -> Self: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __date_string: str) -> Self: ... if sys.version_info >= (3, 8): @classmethod - def fromisocalendar(cls: type[_S], year: int, week: int, day: int) -> _S: ... + def fromisocalendar(cls: type[Self], year: int, week: int, day: int) -> Self: ... @property def year(self) -> int: ... @property @@ -67,10 +67,10 @@ class date: def __ge__(self, __other: date) -> bool: ... def __gt__(self, __other: date) -> bool: ... if sys.version_info >= (3, 8): - def __add__(self: _S, __other: timedelta) -> _S: ... - def __radd__(self: _S, __other: timedelta) -> _S: ... + def __add__(self: Self, __other: timedelta) -> Self: ... + def __radd__(self: Self, __other: timedelta) -> Self: ... @overload - def __sub__(self: _D, __other: timedelta) -> _D: ... + def __sub__(self: Self, __other: timedelta) -> Self: ... @overload def __sub__(self, __other: datetime) -> NoReturn: ... @overload @@ -98,7 +98,7 @@ class time: max: ClassVar[time] resolution: ClassVar[timedelta] def __new__( - cls: type[_S], + cls: type[Self], hour: int = ..., minute: int = ..., second: int = ..., @@ -106,7 +106,7 @@ class time: tzinfo: _tzinfo | None = ..., *, fold: int = ..., - ) -> _S: ... + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -127,7 +127,7 @@ class time: def isoformat(self, timespec: str = ...) -> str: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: type[_S], __time_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __time_string: str) -> Self: ... def strftime(self, __format: str) -> str: ... def __format__(self, __fmt: str) -> str: ... def utcoffset(self) -> timedelta | None: ... @@ -152,7 +152,7 @@ class timedelta(SupportsAbs[timedelta]): max: ClassVar[timedelta] resolution: ClassVar[timedelta] def __new__( - cls: type[_S], + cls: type[Self], days: float = ..., seconds: float = ..., microseconds: float = ..., @@ -160,7 +160,7 @@ class timedelta(SupportsAbs[timedelta]): minutes: float = ..., hours: float = ..., weeks: float = ..., - ) -> _S: ... + ) -> Self: ... @property def days(self) -> int: ... @property @@ -199,7 +199,7 @@ class datetime(date): max: ClassVar[datetime] resolution: ClassVar[timedelta] def __new__( - cls: type[_S], + cls: type[Self], year: int, month: int, day: int, @@ -210,7 +210,7 @@ class datetime(date): tzinfo: _tzinfo | None = ..., *, fold: int = ..., - ) -> _S: ... + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -227,26 +227,26 @@ class datetime(date): # but it is named "timestamp" in the C implementation and "t" in the Python implementation, # so it is only truly *safe* to pass it as a positional argument. @classmethod - def fromtimestamp(cls: type[_S], __timestamp: float, tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float, tz: _tzinfo | None = ...) -> Self: ... @classmethod - def utcfromtimestamp(cls: type[_S], __t: float) -> _S: ... + def utcfromtimestamp(cls: type[Self], __t: float) -> Self: ... if sys.version_info >= (3, 8): @classmethod - def now(cls: type[_S], tz: _tzinfo | None = ...) -> _S: ... + def now(cls: type[Self], tz: _tzinfo | None = ...) -> Self: ... else: @overload @classmethod - def now(cls: type[_S], tz: None = ...) -> _S: ... + def now(cls: type[Self], tz: None = ...) -> Self: ... @overload @classmethod def now(cls, tz: _tzinfo) -> datetime: ... @classmethod - def utcnow(cls: type[_S]) -> _S: ... + def utcnow(cls: type[Self]) -> Self: ... @classmethod def combine(cls, date: _date, time: _time, tzinfo: _tzinfo | None = ...) -> datetime: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __date_string: str) -> Self: ... def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... @@ -266,7 +266,7 @@ class datetime(date): fold: int = ..., ) -> datetime: ... if sys.version_info >= (3, 8): - def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... + def astimezone(self: Self, tz: _tzinfo | None = ...) -> Self: ... else: def astimezone(self, tz: _tzinfo | None = ...) -> datetime: ... def ctime(self) -> str: ... @@ -282,7 +282,7 @@ class datetime(date): def __gt__(self, __other: datetime) -> bool: ... # type: ignore[override] if sys.version_info >= (3, 8): @overload # type: ignore[override] - def __sub__(self: _D, __other: timedelta) -> _D: ... + def __sub__(self: Self, __other: timedelta) -> Self: ... @overload def __sub__(self: _D, __other: _D) -> timedelta: ... else: diff --git a/stdlib/decimal.pyi b/stdlib/decimal.pyi index 0fce0cb5aed1..a7fe060a4132 100644 --- a/stdlib/decimal.pyi +++ b/stdlib/decimal.pyi @@ -1,12 +1,12 @@ import numbers import sys +from _typeshed import Self from types import TracebackType -from typing import Any, Container, NamedTuple, Sequence, TypeVar, Union, overload +from typing import Any, Container, NamedTuple, Sequence, Union, overload _Decimal = Union[Decimal, int] _DecimalNew = Union[Decimal, float, str, tuple[int, Sequence[int], int]] _ComparableNum = Union[Decimal, float, numbers.Rational] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): sign: int @@ -50,7 +50,7 @@ def getcontext() -> Context: ... def localcontext(ctx: Context | None = ...) -> _ContextManager: ... class Decimal: - def __new__(cls: type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... + def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... @classmethod def from_float(cls, __f: float) -> Decimal: ... def __bool__(self) -> bool: ... diff --git a/stdlib/distutils/version.pyi b/stdlib/distutils/version.pyi index 1908cdeda97a..846e1d178800 100644 --- a/stdlib/distutils/version.pyi +++ b/stdlib/distutils/version.pyi @@ -1,38 +1,37 @@ +from _typeshed import Self from abc import abstractmethod -from typing import Pattern, TypeVar - -_T = TypeVar("_T", bound=Version) +from typing import Pattern class Version: def __repr__(self) -> str: ... def __eq__(self, other: object) -> bool: ... - def __lt__(self: _T, other: _T | str) -> bool: ... - def __le__(self: _T, other: _T | str) -> bool: ... - def __gt__(self: _T, other: _T | str) -> bool: ... - def __ge__(self: _T, other: _T | str) -> bool: ... + def __lt__(self: Self, other: Self | str) -> bool: ... + def __le__(self: Self, other: Self | str) -> bool: ... + def __gt__(self: Self, other: Self | str) -> bool: ... + def __ge__(self: Self, other: Self | str) -> bool: ... @abstractmethod def __init__(self, vstring: str | None = ...) -> None: ... @abstractmethod - def parse(self: _T, vstring: str) -> _T: ... + def parse(self: Self, vstring: str) -> Self: ... @abstractmethod def __str__(self) -> str: ... @abstractmethod - def _cmp(self: _T, other: _T | str) -> bool: ... + def _cmp(self: Self, other: Self | str) -> bool: ... class StrictVersion(Version): version_re: Pattern[str] version: tuple[int, int, int] prerelease: tuple[str, int] | None def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... + def parse(self: Self, vstring: str) -> Self: ... def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def _cmp(self: Self, other: Self | str) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] vstring: str version: tuple[str | int, ...] def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... + def parse(self: Self, vstring: str) -> Self: ... def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def _cmp(self: Self, other: Self | str) -> bool: ... diff --git a/stdlib/email/_header_value_parser.pyi b/stdlib/email/_header_value_parser.pyi index b1389d11e198..1b006c3f7959 100644 --- a/stdlib/email/_header_value_parser.pyi +++ b/stdlib/email/_header_value_parser.pyi @@ -1,11 +1,10 @@ import sys +from _typeshed import Self from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, Pattern, TypeVar, Union +from typing import Any, Iterable, Iterator, Pattern, Union from typing_extensions import Final -_T = TypeVar("_T") - WSP: Final[set[str]] CFWS_LEADER: Final[set[str]] SPECIALS: Final[set[str]] @@ -327,7 +326,7 @@ class Terminal(str): syntactic_break: bool token_type: str defects: list[MessageDefect] - def __new__(cls: type[_T], value: str, token_type: str) -> _T: ... + def __new__(cls: type[Self], value: str, token_type: str) -> Self: ... def pprint(self) -> None: ... @property def all_defects(self) -> list[MessageDefect]: ... diff --git a/stdlib/enum.pyi b/stdlib/enum.pyi index b10b64546cb5..6b7a680fc572 100644 --- a/stdlib/enum.pyi +++ b/stdlib/enum.pyi @@ -1,5 +1,6 @@ import sys import types +from _typeshed import Self from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping @@ -32,7 +33,7 @@ class _EnumDict(dict[str, Any]): class EnumMeta(ABCMeta): if sys.version_info >= (3, 11): def __new__( - metacls: type[_T], + metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, @@ -40,11 +41,11 @@ class EnumMeta(ABCMeta): boundary: FlagBoundary | None = ..., _simple: bool = ..., **kwds: Any, - ) -> _T: ... + ) -> Self: ... elif sys.version_info >= (3, 9): - def __new__(metacls: type[_T], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any) -> _T: ... # type: ignore + def __new__(metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any) -> Self: ... # type: ignore else: - def __new__(metacls: type[_T], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> _T: ... # type: ignore + def __new__(metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> Self: ... # type: ignore def __iter__(self: type[_T]) -> Iterator[_T]: ... def __reversed__(self: type[_T]) -> Iterator[_T]: ... def __contains__(self: type[Any], member: object) -> bool: ... @@ -112,7 +113,7 @@ class Enum(metaclass=EnumMeta): def _missing_(cls, value: object) -> Any: ... @staticmethod def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: ... - def __new__(cls: type[_T], value: object) -> _T: ... + def __new__(cls: type[Self], value: object) -> Self: ... def __dir__(self) -> list[str]: ... def __format__(self, format_spec: str) -> str: ... def __hash__(self) -> Any: ... @@ -126,7 +127,7 @@ class IntEnum(int, Enum): else: @types.DynamicClassAttribute def value(self) -> int: ... - def __new__(cls: type[_T], value: int | _T) -> _T: ... + def __new__(cls: type[Self], value: int | Self) -> Self: ... def unique(enumeration: _S) -> _S: ... @@ -141,7 +142,7 @@ class auto(IntFlag): else: @types.DynamicClassAttribute def value(self) -> Any: ... - def __new__(cls: type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... class Flag(Enum): _name_: str | None # type: ignore[assignment] @@ -158,23 +159,23 @@ class Flag(Enum): def value(self) -> int: ... def __contains__(self: _T, other: _T) -> bool: ... def __bool__(self) -> bool: ... - def __or__(self: _T, other: _T) -> _T: ... - def __and__(self: _T, other: _T) -> _T: ... - def __xor__(self: _T, other: _T) -> _T: ... - def __invert__(self: _T) -> _T: ... + def __or__(self: Self, other: Self) -> Self: ... + def __and__(self: Self, other: Self) -> Self: ... + def __xor__(self: Self, other: Self) -> Self: ... + def __invert__(self: Self) -> Self: ... class IntFlag(int, Flag): - def __new__(cls: type[_T], value: int | _T) -> _T: ... - def __or__(self: _T, other: int | _T) -> _T: ... - def __and__(self: _T, other: int | _T) -> _T: ... - def __xor__(self: _T, other: int | _T) -> _T: ... - def __ror__(self: _T, n: int | _T) -> _T: ... - def __rand__(self: _T, n: int | _T) -> _T: ... - def __rxor__(self: _T, n: int | _T) -> _T: ... + def __new__(cls: type[Self], value: int | Self) -> Self: ... + def __or__(self: Self, other: int | Self) -> Self: ... + def __and__(self: Self, other: int | Self) -> Self: ... + def __xor__(self: Self, other: int | Self) -> Self: ... + def __ror__(self: Self, n: int | Self) -> Self: ... + def __rand__(self: Self, n: int | Self) -> Self: ... + def __rxor__(self: Self, n: int | Self) -> Self: ... if sys.version_info >= (3, 11): class StrEnum(str, Enum): - def __new__(cls: type[_T], value: str | _T) -> _T: ... + def __new__(cls: type[Self], value: str | Self) -> Self: ... _value_: str @property def value(self) -> str: ... diff --git a/stdlib/fractions.pyi b/stdlib/fractions.pyi index 9536e511ef3c..56a6f0c078d2 100644 --- a/stdlib/fractions.pyi +++ b/stdlib/fractions.pyi @@ -1,11 +1,11 @@ import sys +from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import TypeVar, Union, overload +from typing import Union, overload from typing_extensions import Literal _ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") if sys.version_info < (3, 9): @overload @@ -20,10 +20,10 @@ if sys.version_info < (3, 9): class Fraction(Rational): @overload def __new__( - cls: type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... + cls: type[Self], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... + ) -> Self: ... @overload - def __new__(cls: type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... + def __new__(cls: type[Self], __value: float | Decimal | str, *, _normalize: bool = ...) -> Self: ... @classmethod def from_float(cls, f: float) -> Fraction: ... @classmethod diff --git a/stdlib/functools.pyi b/stdlib/functools.pyi index ff1c3fad69bb..6a8a990b37fa 100644 --- a/stdlib/functools.pyi +++ b/stdlib/functools.pyi @@ -1,6 +1,6 @@ import sys import types -from _typeshed import SupportsAllComparisons, SupportsItems +from _typeshed import Self, SupportsAllComparisons, SupportsItems from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, TypeVar, overload from typing_extensions import final @@ -51,7 +51,7 @@ class partial(Generic[_T]): func: Callable[..., _T] args: tuple[Any, ...] keywords: dict[str, Any] - def __new__(cls: type[_S], __func: Callable[..., _T], *args: Any, **kwargs: Any) -> _S: ... + def __new__(cls: type[Self], __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ... def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/stdlib/ipaddress.pyi b/stdlib/ipaddress.pyi index 6af3ebc3a2bd..0b29f2633d05 100644 --- a/stdlib/ipaddress.pyi +++ b/stdlib/ipaddress.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, Container, Generic, Iterable, Iterator, SupportsInt, TypeVar, overload # Undocumented length constants @@ -7,7 +8,6 @@ IPV6LENGTH: int _A = TypeVar("_A", IPv4Address, IPv6Address) _N = TypeVar("_N", IPv4Network, IPv6Network) -_T = TypeVar("_T") def ip_address(address: object) -> IPv4Address | IPv6Address: ... def ip_network(address: object, strict: bool = ...) -> IPv4Network | IPv6Network: ... @@ -15,10 +15,10 @@ def ip_interface(address: object) -> IPv4Interface | IPv6Interface: ... class _IPAddressBase: def __eq__(self, other: Any) -> bool: ... - def __ge__(self: _T, other: _T) -> bool: ... - def __gt__(self: _T, other: _T) -> bool: ... - def __le__(self: _T, other: _T) -> bool: ... - def __lt__(self: _T, other: _T) -> bool: ... + def __ge__(self: Self, other: Self) -> bool: ... + def __gt__(self: Self, other: Self) -> bool: ... + def __le__(self: Self, other: Self) -> bool: ... + def __lt__(self: Self, other: Self) -> bool: ... def __ne__(self, other: Any) -> bool: ... @property def compressed(self) -> str: ... @@ -31,10 +31,10 @@ class _IPAddressBase: class _BaseAddress(_IPAddressBase, SupportsInt): def __init__(self, address: object) -> None: ... - def __add__(self: _T, other: int) -> _T: ... + def __add__(self: Self, other: int) -> Self: ... def __hash__(self) -> int: ... def __int__(self) -> int: ... - def __sub__(self: _T, other: int) -> _T: ... + def __sub__(self: Self, other: int) -> Self: ... @property def is_global(self) -> bool: ... @property @@ -61,10 +61,10 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): def __contains__(self, other: Any) -> bool: ... def __getitem__(self, n: int) -> _A: ... def __iter__(self) -> Iterator[_A]: ... - def address_exclude(self: _T, other: _T) -> Iterator[_T]: ... + def address_exclude(self: Self, other: Self) -> Iterator[Self]: ... @property def broadcast_address(self) -> _A: ... - def compare_networks(self: _T, other: _T) -> int: ... + def compare_networks(self: Self, other: Self) -> int: ... def hosts(self) -> Iterator[_A]: ... @property def is_global(self) -> bool: ... @@ -88,10 +88,10 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): @property def prefixlen(self) -> int: ... if sys.version_info >= (3, 7): - def subnet_of(self: _T, other: _T) -> bool: ... - def supernet_of(self: _T, other: _T) -> bool: ... - def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Iterator[_T]: ... - def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> _T: ... + def subnet_of(self: Self, other: Self) -> bool: ... + def supernet_of(self: Self, other: Self) -> bool: ... + def subnets(self: Self, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Iterator[Self]: ... + def supernet(self: Self, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Self: ... @property def with_hostmask(self) -> str: ... @property diff --git a/stdlib/lib2to3/pgen2/grammar.pyi b/stdlib/lib2to3/pgen2/grammar.pyi index 77cc6aec3d67..3c3b90c52f7c 100644 --- a/stdlib/lib2to3/pgen2/grammar.pyi +++ b/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,7 +1,6 @@ -from _typeshed import StrPath -from typing import Optional, TypeVar +from _typeshed import Self, StrPath +from typing import Optional -_P = TypeVar("_P") _Label = tuple[int, Optional[str]] _DFA = list[list[tuple[int, int]]] _DFAS = tuple[_DFA, dict[int, int]] @@ -19,7 +18,7 @@ class Grammar: def __init__(self) -> None: ... def dump(self, filename: StrPath) -> None: ... def load(self, filename: StrPath) -> None: ... - def copy(self: _P) -> _P: ... + def copy(self: Self) -> Self: ... def report(self) -> None: ... opmap_raw: str diff --git a/stdlib/lib2to3/pytree.pyi b/stdlib/lib2to3/pytree.pyi index 2ed9a2788d84..aefd3014617e 100644 --- a/stdlib/lib2to3/pytree.pyi +++ b/stdlib/lib2to3/pytree.pyi @@ -1,7 +1,7 @@ +from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator, Optional, TypeVar, Union +from typing import Any, Callable, Iterator, Optional, Union -_P = TypeVar("_P") _NL = Union[Node, Leaf] _Context = tuple[str, int, int] _Results = dict[str, _NL] @@ -20,8 +20,8 @@ class Base: was_changed: bool was_checked: bool def __eq__(self, other: Any) -> bool: ... - def _eq(self: _P, other: _P) -> bool: ... - def clone(self: _P) -> _P: ... + def _eq(self: Self, other: Self) -> bool: ... + def clone(self: Self) -> Self: ... def post_order(self) -> Iterator[_NL]: ... def pre_order(self) -> Iterator[_NL]: ... def replace(self, new: _NL | list[_NL]) -> None: ... diff --git a/stdlib/multiprocessing/pool.pyi b/stdlib/multiprocessing/pool.pyi index 70098bde7e74..7c2fd8a06a69 100644 --- a/stdlib/multiprocessing/pool.pyi +++ b/stdlib/multiprocessing/pool.pyi @@ -59,7 +59,7 @@ class IMapIterator(Iterator[_T]): def __init__(self, pool: Pool) -> None: ... else: def __init__(self, cache: dict[int, IMapIterator[Any]]) -> None: ... - def __iter__(self: _S) -> _S: ... + def __iter__(self: Self) -> Self: ... def next(self, timeout: float | None = ...) -> _T: ... def __next__(self, timeout: float | None = ...) -> _T: ... diff --git a/stdlib/pathlib.pyi b/stdlib/pathlib.pyi index 9db873287a1f..3313bae9c2d9 100644 --- a/stdlib/pathlib.pyi +++ b/stdlib/pathlib.pyi @@ -11,14 +11,12 @@ from _typeshed import ( 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, TypeVar, overload +from typing import IO, Any, BinaryIO, Generator, Sequence, overload from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias -_P = TypeVar("_P", bound=PurePath) - class PurePath(PathLike[str]): parts: tuple[str, ...] drive: str @@ -28,14 +26,14 @@ class PurePath(PathLike[str]): suffix: str suffixes: list[str] stem: str - def __new__(cls: type[_P], *args: StrPath) -> _P: ... + def __new__(cls: type[Self], *args: StrPath) -> Self: ... def __hash__(self) -> int: ... def __lt__(self, other: PurePath) -> bool: ... def __le__(self, other: PurePath) -> bool: ... def __gt__(self, other: PurePath) -> bool: ... def __ge__(self, other: PurePath) -> bool: ... - def __truediv__(self: _P, key: StrPath) -> _P: ... - def __rtruediv__(self: _P, key: StrPath) -> _P: ... + def __truediv__(self: Self, key: StrPath) -> Self: ... + def __rtruediv__(self: Self, key: StrPath) -> Self: ... def __bytes__(self) -> bytes: ... def as_posix(self) -> str: ... def as_uri(self) -> str: ... @@ -44,16 +42,16 @@ class PurePath(PathLike[str]): if sys.version_info >= (3, 9): def is_relative_to(self, *other: StrPath) -> bool: ... def match(self, path_pattern: str) -> bool: ... - def relative_to(self: _P, *other: StrPath) -> _P: ... - def with_name(self: _P, name: str) -> _P: ... + def relative_to(self: Self, *other: StrPath) -> Self: ... + def with_name(self: Self, name: str) -> Self: ... if sys.version_info >= (3, 9): - def with_stem(self: _P, stem: str) -> _P: ... - def with_suffix(self: _P, suffix: str) -> _P: ... - def joinpath(self: _P, *other: StrPath) -> _P: ... + def with_stem(self: Self, stem: str) -> Self: ... + def with_suffix(self: Self, suffix: str) -> Self: ... + def joinpath(self: Self, *other: StrPath) -> Self: ... @property - def parents(self: _P) -> Sequence[_P]: ... + def parents(self: Self) -> Sequence[Self]: ... @property - def parent(self: _P) -> _P: ... + def parent(self: Self) -> Self: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, type: Any) -> GenericAlias: ... @@ -61,13 +59,13 @@ class PurePosixPath(PurePath): ... class PureWindowsPath(PurePath): ... class Path(PurePath): - def __new__(cls: type[_P], *args: StrPath, **kwargs: Any) -> _P: ... + def __new__(cls: type[Self], *args: StrPath, **kwargs: Any) -> Self: ... def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... @classmethod - def cwd(cls: type[_P]) -> _P: ... + def cwd(cls: type[Self]) -> Self: ... if sys.version_info >= (3, 10): def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... def chmod(self, mode: int, *, follow_symlinks: bool = ...) -> None: ... @@ -75,7 +73,7 @@ class Path(PurePath): def stat(self) -> stat_result: ... def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... - def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... + def glob(self: Self, pattern: str) -> Generator[Self, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... @@ -86,7 +84,7 @@ class Path(PurePath): def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... - def iterdir(self: _P) -> Generator[_P, None, None]: ... + def iterdir(self: Self) -> Generator[Self, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... @@ -147,15 +145,15 @@ class Path(PurePath): ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): - def readlink(self: _P) -> _P: ... + def readlink(self: Self) -> Self: ... if sys.version_info >= (3, 8): - def rename(self: _P, target: str | PurePath) -> _P: ... - def replace(self: _P, target: str | PurePath) -> _P: ... + def rename(self: Self, target: str | PurePath) -> Self: ... + def replace(self: Self, target: str | PurePath) -> Self: ... else: def rename(self, target: str | PurePath) -> None: ... def replace(self, target: str | PurePath) -> None: ... - def resolve(self: _P, strict: bool = ...) -> _P: ... - def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... + def resolve(self: Self, strict: bool = ...) -> Self: ... + def rglob(self: Self, pattern: str) -> Generator[Self, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: str | Path, target_is_directory: bool = ...) -> None: ... if sys.version_info >= (3, 10): @@ -166,9 +164,9 @@ class Path(PurePath): else: def unlink(self) -> None: ... @classmethod - def home(cls: type[_P]) -> _P: ... - def absolute(self: _P) -> _P: ... - def expanduser(self: _P) -> _P: ... + def home(cls: type[Self]) -> Self: ... + def absolute(self: Self) -> Self: ... + def expanduser(self: Self) -> Self: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... def samefile(self, other_path: str | bytes | int | Path) -> bool: ... diff --git a/stdlib/profile.pyi b/stdlib/profile.pyi index 7581c0122c9c..007a1a11da12 100644 --- a/stdlib/profile.pyi +++ b/stdlib/profile.pyi @@ -1,4 +1,4 @@ -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from typing import Any, Callable, TypeVar def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... @@ -6,7 +6,6 @@ def runctx( statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") _Label = tuple[str, int, str] @@ -21,7 +20,7 @@ class Profile: def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> _SelfT: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/stdlib/pstats.pyi b/stdlib/pstats.pyi index 6e008c823ff2..1328308467f0 100644 --- a/stdlib/pstats.pyi +++ b/stdlib/pstats.pyi @@ -1,11 +1,10 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, TypeVar, Union, overload +from typing import IO, Any, Iterable, Union, overload _Selector = Union[str, float, int] -_T = TypeVar("_T", bound=Stats) if sys.version_info >= (3, 7): from enum import Enum @@ -23,29 +22,29 @@ if sys.version_info >= (3, 7): class Stats: sort_arg_dict_default: dict[str, tuple[Any, str]] def __init__( - self: _T, + self: Self, __arg: None | str | Profile | _cProfile = ..., - *args: None | str | Profile | _cProfile | _T, + *args: None | str | Profile | _cProfile | Self, stream: IO[Any] | None = ..., ) -> None: ... def init(self, arg: None | str | Profile | _cProfile) -> None: ... def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Profile | _cProfile | _T) -> _T: ... + def add(self: Self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: ... def get_sort_arg_defs(self) -> dict[str, tuple[tuple[tuple[int, int], ...], str]]: ... @overload - def sort_stats(self: _T, field: int) -> _T: ... + def sort_stats(self: Self, field: int) -> Self: ... @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... + def sort_stats(self: Self, *field: str) -> Self: ... + def reverse_order(self: Self) -> Self: ... + def strip_dirs(self: Self) -> Self: ... def calc_callees(self) -> None: ... def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ... - def print_stats(self: _T, *amount: _Selector) -> _T: ... - def print_callees(self: _T, *amount: _Selector) -> _T: ... - def print_callers(self: _T, *amount: _Selector) -> _T: ... + def print_stats(self: Self, *amount: _Selector) -> Self: ... + def print_callees(self: Self, *amount: _Selector) -> Self: ... + def print_callers(self: Self, *amount: _Selector) -> Self: ... def print_call_heading(self, name_size: int, column_title: str) -> None: ... def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = ...) -> None: ... def print_title(self) -> None: ... diff --git a/stdlib/shlex.pyi b/stdlib/shlex.pyi index dfe554b0a773..a979ac07793d 100644 --- a/stdlib/shlex.pyi +++ b/stdlib/shlex.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Iterable, TextIO, TypeVar +from _typeshed import Self +from typing import Any, Iterable, TextIO def split(s: str, comments: bool = ..., posix: bool = ...) -> list[str]: ... @@ -8,8 +9,6 @@ if sys.version_info >= (3, 8): def quote(s: str) -> str: ... -_SLT = TypeVar("_SLT", bound=shlex) - class shlex(Iterable[str]): commenters: str wordchars: str @@ -41,5 +40,5 @@ class shlex(Iterable[str]): def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... def pop_source(self) -> None: ... def error_leader(self, infile: str | None = ..., lineno: int | None = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> str: ... diff --git a/stdlib/socket.pyi b/stdlib/socket.pyi index 01d378deb245..e97a66f5e8c5 100644 --- a/stdlib/socket.pyi +++ b/stdlib/socket.pyi @@ -3,7 +3,7 @@ from _typeshed import ReadableBuffer, Self, WriteableBuffer from collections.abc import Iterable from enum import IntEnum, IntFlag from io import RawIOBase -from typing import Any, BinaryIO, TextIO, TypeVar, overload +from typing import Any, BinaryIO, TextIO, overload from typing_extensions import Literal # Ideally, we'd just do "from _socket import *". Unfortunately, socket @@ -380,8 +380,6 @@ if sys.platform == "win32": SIO_RCVALL as SIO_RCVALL, ) -_T = TypeVar("_T") - # Re-exported from errno EBADF: int EAGAIN: int @@ -546,7 +544,7 @@ class socket(_socket.socket): ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__(self, *args: object) -> None: ... - def dup(self: _T) -> _T: ... # noqa: F811 + def dup(self: Self) -> Self: ... # noqa: F811 def accept(self) -> tuple[socket, _RetAddress]: ... # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded diff --git a/stdlib/statistics.pyi b/stdlib/statistics.pyi index b92a05466d05..8437a43ffff1 100644 --- a/stdlib/statistics.pyi +++ b/stdlib/statistics.pyi @@ -1,10 +1,9 @@ import sys -from _typeshed import SupportsRichComparisonT +from _typeshed import Self, SupportsRichComparisonT from decimal import Decimal from fractions import Fraction from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar, Union -_T = TypeVar("_T") # Most functions in this module accept homogeneous collections of one of these types _Number = Union[float, Decimal, Fraction] _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) @@ -58,7 +57,7 @@ if sys.version_info >= (3, 8): @property def variance(self) -> float: ... @classmethod - def from_samples(cls: type[_T], data: Iterable[SupportsFloat]) -> _T: ... + def from_samples(cls: type[Self], data: Iterable[SupportsFloat]) -> Self: ... def samples(self, n: int, *, seed: Any | None = ...) -> list[float]: ... def pdf(self, x: float) -> float: ... def cdf(self, x: float) -> float: ... diff --git a/stdlib/tarfile.pyi b/stdlib/tarfile.pyi index 73b50c298294..c98608d49693 100644 --- a/stdlib/tarfile.pyi +++ b/stdlib/tarfile.pyi @@ -5,11 +5,9 @@ from _typeshed import Self, StrOrBytesPath, StrPath from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, Protocol, TypeVar, overload +from typing import IO, Protocol, overload from typing_extensions import Literal -_TF = TypeVar("_TF", bound=TarFile) - class _Fileobj(Protocol): def read(self, __size: int) -> bytes: ... def write(self, __b: bytes) -> object: ... @@ -133,7 +131,7 @@ class TarFile: def __iter__(self) -> Iterator[TarInfo]: ... @classmethod def open( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None = ..., mode: str = ..., fileobj: IO[bytes] | None = ..., # depends on mode @@ -148,10 +146,10 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @classmethod def taropen( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r", "a", "w", "x"] = ..., fileobj: _Fileobj | None = ..., @@ -165,11 +163,11 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def gzopen( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r"] = ..., fileobj: _GzipReadableFileobj | None = ..., @@ -183,11 +181,11 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def gzopen( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["w", "x"], fileobj: _GzipWritableFileobj | None = ..., @@ -201,11 +199,11 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def bz2open( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["w", "x"], fileobj: _Bz2WritableFileobj | None = ..., @@ -219,11 +217,11 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def bz2open( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r"] = ..., fileobj: _Bz2ReadableFileobj | None = ..., @@ -237,10 +235,10 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @classmethod def xzopen( - cls: type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r", "w", "x"] = ..., fileobj: IO[bytes] | None = ..., @@ -254,7 +252,7 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> _list[TarInfo]: ... def getnames(self) -> _list[str]: ... diff --git a/stdlib/turtle.pyi b/stdlib/turtle.pyi index c74a151f68b5..521ac5838b62 100644 --- a/stdlib/turtle.pyi +++ b/stdlib/turtle.pyi @@ -1,5 +1,6 @@ +from _typeshed import Self from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar -from typing import Any, Callable, ClassVar, Sequence, TypeVar, Union, overload +from typing import Any, Callable, ClassVar, Sequence, Union, overload # Note: '_Color' is the alias we use for arguments and _AnyColor is the # alias we use for return types. Really, these two aliases should be the @@ -215,8 +216,6 @@ class TPen: st = showturtle ht = hideturtle -_T = TypeVar("_T") - class RawTurtle(TPen, TNavigator): screen: TurtleScreen screens: ClassVar[list[TurtleScreen]] @@ -227,7 +226,7 @@ class RawTurtle(TPen, TNavigator): def setundobuffer(self, size: int | None) -> None: ... def undobufferentries(self) -> int: ... def clear(self) -> None: ... - def clone(self: _T) -> _T: ... + def clone(self: Self) -> Self: ... @overload def shape(self, name: None = ...) -> str: ... @overload @@ -272,7 +271,7 @@ class RawTurtle(TPen, TNavigator): def end_poly(self) -> None: ... def get_poly(self) -> _PolygonCoords | None: ... def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... + def getturtle(self: Self) -> Self: ... getpen = getturtle def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... diff --git a/stdlib/typing.pyi b/stdlib/typing.pyi index 925ade3d6859..1ec9ba720545 100644 --- a/stdlib/typing.pyi +++ b/stdlib/typing.pyi @@ -1,6 +1,6 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys -from _typeshed import SupportsKeysAndGetItem +from _typeshed import Self, SupportsKeysAndGetItem from abc import ABCMeta, abstractmethod from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final @@ -702,11 +702,11 @@ class NamedTuple(Tuple[Any, ...]): def _asdict(self) -> dict[str, Any]: ... else: def _asdict(self) -> collections.OrderedDict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... + def _replace(self: Self, **kwargs: Any) -> Self: ... # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=ABCMeta): - def copy(self: _T) -> _T: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... @@ -717,8 +717,8 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... def values(self) -> ValuesView[object]: ... - def __or__(self: _T, __value: _T) -> _T: ... - def __ior__(self: _T, __value: _T) -> _T: ... + def __or__(self: Self, __value: Self) -> Self: ... + def __ior__(self: Self, __value: Self) -> Self: ... # This itself is only available during type checking def type_check_only(func_or_cls: _F) -> _F: ... diff --git a/stdlib/urllib/response.pyi b/stdlib/urllib/response.pyi index c52b96e0796d..9065f3a94ccb 100644 --- a/stdlib/urllib/response.pyi +++ b/stdlib/urllib/response.pyi @@ -2,9 +2,7 @@ import sys from _typeshed import Self from email.message import Message from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, TypeVar - -_AIUT = TypeVar("_AIUT", bound=addbase) +from typing import IO, Any, BinaryIO, Callable, Iterable class addbase(BinaryIO): fp: IO[bytes] @@ -13,7 +11,7 @@ class addbase(BinaryIO): def __exit__( self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... - def __iter__(self: _AIUT) -> _AIUT: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> bytes: ... def close(self) -> None: ... # These methods don't actually exist, but the class inherits at runtime from diff --git a/stdlib/zoneinfo/__init__.pyi b/stdlib/zoneinfo/__init__.pyi index 1170b354874a..36e483953b1d 100644 --- a/stdlib/zoneinfo/__init__.pyi +++ b/stdlib/zoneinfo/__init__.pyi @@ -1,5 +1,5 @@ import typing -from _typeshed import StrPath +from _typeshed import Self, StrPath from datetime import tzinfo from typing import Any, Iterable, Protocol, Sequence @@ -14,9 +14,9 @@ class ZoneInfo(tzinfo): def key(self) -> str: ... def __init__(self, key: str) -> None: ... @classmethod - def no_cache(cls: type[_T], key: str) -> _T: ... + def no_cache(cls: type[Self], key: str) -> Self: ... @classmethod - def from_file(cls: type[_T], __fobj: _IOBytes, key: str | None = ...) -> _T: ... + def from_file(cls: type[Self], __fobj: _IOBytes, key: str | None = ...) -> Self: ... @classmethod def clear_cache(cls, *, only_keys: Iterable[str] = ...) -> None: ... diff --git a/stubs/Markdown/markdown/core.pyi b/stubs/Markdown/markdown/core.pyi index e43df00dfdb1..c1c527872139 100644 --- a/stubs/Markdown/markdown/core.pyi +++ b/stubs/Markdown/markdown/core.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from typing import Any, BinaryIO, Callable, ClassVar, Mapping, Sequence, Text, TextIO from typing_extensions import Literal from xml.etree.ElementTree import Element @@ -30,7 +31,7 @@ class Markdown: def registerExtensions(self, extensions: Sequence[Extension | str], configs: Mapping[str, Mapping[str, Any]]) -> Markdown: ... def build_extension(self, ext_name: Text, configs: Mapping[str, str]) -> Extension: ... def registerExtension(self, extension: Extension) -> Markdown: ... - def reset(self: Markdown) -> Markdown: ... + def reset(self: Self) -> Self: ... def set_output_format(self, format: Literal["xhtml", "html"]) -> Markdown: ... def is_block_level(self, tag: str) -> bool: ... def convert(self, source: Text) -> Text: ... diff --git a/stubs/Pillow/PIL/ImageFile.pyi b/stubs/Pillow/PIL/ImageFile.pyi index 21bfde2e188b..44560903ab78 100644 --- a/stubs/Pillow/PIL/ImageFile.pyi +++ b/stubs/Pillow/PIL/ImageFile.pyi @@ -1,9 +1,8 @@ -from typing import Any, NoReturn, TypeVar +from _typeshed import Self +from typing import Any, NoReturn from .Image import Image -_T = TypeVar("_T") - MAXBLOCK: int SAFEBLOCK: Any LOAD_TRUNCATED_IMAGES: bool @@ -41,7 +40,7 @@ class Parser: def reset(self) -> None: ... decode: Any def feed(self, data) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def close(self) -> Image: ... diff --git a/stubs/PyMySQL/pymysql/cursors.pyi b/stubs/PyMySQL/pymysql/cursors.pyi index be38c5494027..23911f0d54a2 100644 --- a/stubs/PyMySQL/pymysql/cursors.pyi +++ b/stubs/PyMySQL/pymysql/cursors.pyi @@ -1,9 +1,8 @@ -from typing import Any, Iterable, Iterator, Text, TypeVar +from _typeshed import Self +from typing import Any, Iterable, Iterator, Text from .connections import Connection -_SelfT = TypeVar("_SelfT") - class Cursor: connection: Connection[Any] description: tuple[Text, ...] @@ -24,7 +23,7 @@ class Cursor: def executemany(self, query: Text, args: Iterable[object]) -> int | None: ... def callproc(self, procname: Text, args: Iterable[Any] = ...) -> Any: ... def scroll(self, value: int, mode: Text = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *exc_info: Any) -> None: ... # Methods returning result tuples are below. def fetchone(self) -> tuple[Any, ...] | None: ... diff --git a/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi b/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi index 35fe7c230540..073d5a6b50c9 100644 --- a/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi +++ b/stubs/SQLAlchemy/sqlalchemy/util/langhelpers.pyi @@ -1,10 +1,10 @@ +from _typeshed import Self from collections.abc import Callable from typing import Any, Generic, TypeVar, overload from . import compat _R = TypeVar("_R") -_T = TypeVar("_T") def md5_hex(x): ... @@ -65,7 +65,7 @@ class memoized_property(Generic[_R]): __name__: str def __init__(self, fget: Callable[..., _R], doc: str | None = ...) -> None: ... @overload - def __get__(self: _T, obj: None, cls: object) -> _T: ... + def __get__(self: Self, obj: None, cls: object) -> Self: ... @overload def __get__(self, obj: object, cls: object) -> _R: ... @classmethod @@ -80,7 +80,7 @@ class HasMemoized: __name__: str def __init__(self, fget: Callable[..., _R], doc: str | None = ...) -> None: ... @overload - def __get__(self: _T, obj: None, cls: object) -> _T: ... + def __get__(self: Self, obj: None, cls: object) -> Self: ... @overload def __get__(self, obj: object, cls: object) -> _R: ... @classmethod @@ -113,7 +113,7 @@ class hybridproperty(Generic[_R]): def __get__(self, instance: None, owner: Any) -> _R: ... @overload def __get__(self, instance: object, owner: object) -> _R: ... - def classlevel(self: _T, func: Callable[..., _R]) -> _T: ... + def classlevel(self: Self, func: Callable[..., _R]) -> Self: ... class hybridmethod: func: Any diff --git a/stubs/croniter/croniter.pyi b/stubs/croniter/croniter.pyi index ea8c5103b401..c55b83672fd7 100644 --- a/stubs/croniter/croniter.pyi +++ b/stubs/croniter/croniter.pyi @@ -1,9 +1,9 @@ import datetime -from typing import Any, Iterator, Text, TypeVar, Union +from _typeshed import Self +from typing import Any, Iterator, Text, Union from typing_extensions import Literal _RetType = Union[type[float], type[datetime.datetime]] -_SelfT = TypeVar("_SelfT", bound=croniter) class CroniterError(ValueError): ... class CroniterBadCronError(CroniterError): ... @@ -53,7 +53,7 @@ class croniter(Iterator[Any]): def get_prev(self, ret_type: _RetType | None = ...) -> Any: ... def get_current(self, ret_type: _RetType | None = ...) -> Any: ... def set_current(self, start_time: float | datetime.datetime) -> float: ... - def __iter__(self: _SelfT) -> _SelfT: ... + def __iter__(self: Self) -> Self: ... def __next__(self, ret_type: _RetType | None = ...) -> Any: ... def next(self, ret_type: _RetType | None = ...) -> Any: ... def all_next(self, ret_type: _RetType | None = ...) -> Iterator[Any]: ... diff --git a/stubs/filelock/filelock/__init__.pyi b/stubs/filelock/filelock/__init__.pyi index 2cb3fe966257..b083297a9b7a 100644 --- a/stubs/filelock/filelock/__init__.pyi +++ b/stubs/filelock/filelock/__init__.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from types import TracebackType class Timeout(TimeoutError): @@ -24,7 +25,7 @@ class BaseFileLock: def is_locked(self) -> bool: ... def acquire(self, timeout: float | None = ..., poll_intervall: float = ...) -> _Acquire_ReturnProxy: ... def release(self, force: bool = ...) -> None: ... - def __enter__(self) -> BaseFileLock: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, traceback: TracebackType | None ) -> None: ... diff --git a/stubs/frozendict/frozendict.pyi b/stubs/frozendict/frozendict.pyi index 238c665e73af..a36f9712f89b 100644 --- a/stubs/frozendict/frozendict.pyi +++ b/stubs/frozendict/frozendict.pyi @@ -1,7 +1,7 @@ import collections +from _typeshed import Self from typing import Any, Generic, Iterable, Iterator, Mapping, TypeVar, overload -_S = TypeVar("_S") _KT = TypeVar("_KT") _VT = TypeVar("_VT") @@ -16,7 +16,7 @@ class frozendict(Mapping[_KT, _VT], Generic[_KT, _VT]): def __init__(self, iterable: Iterable[tuple[_KT, _VT]]) -> None: ... def __getitem__(self, key: _KT) -> _VT: ... def __contains__(self, key: object) -> bool: ... - def copy(self: _S, **add_or_replace: _VT) -> _S: ... + def copy(self: Self, **add_or_replace: _VT) -> Self: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... def __repr__(self) -> str: ... diff --git a/stubs/ldap3/ldap3/core/exceptions.pyi b/stubs/ldap3/ldap3/core/exceptions.pyi index b7b3d6b30903..3958f7cb3804 100644 --- a/stubs/ldap3/ldap3/core/exceptions.pyi +++ b/stubs/ldap3/ldap3/core/exceptions.pyi @@ -1,20 +1,19 @@ import socket -from typing import Any, TypeVar - -_T = TypeVar("_T") +from _typeshed import Self +from typing import Any class LDAPException(Exception): ... class LDAPOperationResult(LDAPException): def __new__( - cls: type[_T], + cls: type[Self], result: Any | None = ..., description: Any | None = ..., dn: Any | None = ..., message: Any | None = ..., response_type: Any | None = ..., response: Any | None = ..., - ) -> _T: ... + ) -> Self: ... result: Any description: Any dn: Any diff --git a/stubs/mypy-extensions/mypy_extensions.pyi b/stubs/mypy-extensions/mypy_extensions.pyi index f5ede45acc06..89f312336b58 100644 --- a/stubs/mypy-extensions/mypy_extensions.pyi +++ b/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,5 +1,6 @@ import abc import sys +from _typeshed import Self from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, TypeVar, ValuesView _T = TypeVar("_T") @@ -7,13 +8,13 @@ _U = TypeVar("_U") # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): - def copy(self: _T) -> _T: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... + def update(self: Self, __m: Self) -> None: ... if sys.version_info >= (3, 0): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... diff --git a/stubs/opentracing/opentracing/scope.pyi b/stubs/opentracing/opentracing/scope.pyi index 3ab00d387ceb..d3ed839fe188 100644 --- a/stubs/opentracing/opentracing/scope.pyi +++ b/stubs/opentracing/opentracing/scope.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from .scope_manager import ScopeManager @@ -10,7 +11,7 @@ class Scope: @property def manager(self) -> ScopeManager: ... def close(self) -> None: ... - def __enter__(self) -> Scope: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... diff --git a/stubs/paramiko/paramiko/_winapi.pyi b/stubs/paramiko/paramiko/_winapi.pyi index 1a302c03f980..8ec689b1099f 100644 --- a/stubs/paramiko/paramiko/_winapi.pyi +++ b/stubs/paramiko/paramiko/_winapi.pyi @@ -1,12 +1,11 @@ import builtins import ctypes import sys +from _typeshed import Self from types import TracebackType -from typing import Any, TypeVar +from typing import Any if sys.platform == "win32": - - _T = TypeVar("_T") def format_system_message(errno: int) -> str | None: ... class WindowsError(builtins.WindowsError): def __init__(self, value: int | None = ...) -> None: ... @@ -32,7 +31,7 @@ if sys.platform == "win32": filemap: Any = ... view: Any = ... def __init__(self, name: str, length: int, security_attributes: Any | None = ...) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def seek(self, pos: int) -> None: ... def write(self, msg: bytes) -> None: ... def read(self, n: int) -> bytes: ... diff --git a/stubs/paramiko/paramiko/pkey.pyi b/stubs/paramiko/paramiko/pkey.pyi index 8d365917590e..b6e25c4f64cc 100644 --- a/stubs/paramiko/paramiko/pkey.pyi +++ b/stubs/paramiko/paramiko/pkey.pyi @@ -1,4 +1,5 @@ -from typing import IO, Pattern, TypeVar +from _typeshed import Self +from typing import IO, Pattern from paramiko.message import Message @@ -6,8 +7,6 @@ OPENSSH_AUTH_MAGIC: bytes = ... def _unpad_openssh(data: bytes) -> bytes: ... -_PK = TypeVar("_PK", bound=PKey) - class PKey: public_blob: PublicBlob | None BEGIN_TAG: Pattern[str] @@ -24,9 +23,9 @@ class PKey: def sign_ssh_data(self, data: bytes) -> Message: ... def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... @classmethod - def from_private_key_file(cls: type[_PK], filename: str, password: str | None = ...) -> _PK: ... + def from_private_key_file(cls: type[Self], filename: str, password: str | None = ...) -> Self: ... @classmethod - def from_private_key(cls: type[_PK], file_obj: IO[str], password: str | None = ...) -> _PK: ... + def from_private_key(cls: type[Self], file_obj: IO[str], password: str | None = ...) -> Self: ... def write_private_key_file(self, filename: str, password: str | None = ...) -> None: ... def write_private_key(self, file_obj: IO[str], password: str | None = ...) -> None: ... def load_certificate(self, value: Message | str) -> None: ... diff --git a/stubs/paramiko/paramiko/util.pyi b/stubs/paramiko/paramiko/util.pyi index 0b72e6462132..ea3eebce7b35 100644 --- a/stubs/paramiko/paramiko/util.pyi +++ b/stubs/paramiko/paramiko/util.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from logging import Logger, LogRecord from types import TracebackType from typing import IO, AnyStr, Callable, Protocol, TypeVar @@ -15,7 +16,6 @@ class SupportsClose(Protocol): def close(self) -> None: ... _T = TypeVar("_T") -_TC = TypeVar("_TC", bound=SupportsClose) def inflate_long(s: bytes, always_positive: bool = ...) -> int: ... @@ -44,7 +44,7 @@ def retry_on_signal(function: Callable[[], _T]) -> _T: ... def constant_time_bytes_eq(a: AnyStr, b: AnyStr) -> bool: ... class ClosingContextManager: - def __enter__(self: _TC) -> _TC: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... diff --git a/stubs/psutil/psutil/__init__.pyi b/stubs/psutil/psutil/__init__.pyi index e5a63e88a438..7b0a1f404c56 100644 --- a/stubs/psutil/psutil/__init__.pyi +++ b/stubs/psutil/psutil/__init__.pyi @@ -1,6 +1,7 @@ import sys +from _typeshed import Self from contextlib import AbstractContextManager -from typing import Any, Callable, Iterable, Iterator, TypeVar +from typing import Any, Callable, Iterable, Iterator from ._common import ( AIX as AIX, @@ -177,11 +178,9 @@ class Process: def kill(self) -> None: ... def wait(self, timeout: int | None = ...) -> int: ... -_Popen = TypeVar("_Popen", bound="Popen") - class Popen(Process): def __init__(self, *args, **kwargs) -> None: ... - def __enter__(self: _Popen) -> _Popen: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args, **kwargs) -> None: ... def __getattribute__(self, name: str) -> Any: ... diff --git a/stubs/python-dateutil/dateutil/_common.pyi b/stubs/python-dateutil/dateutil/_common.pyi index a437f85035a3..71d72ce292d0 100644 --- a/stubs/python-dateutil/dateutil/_common.pyi +++ b/stubs/python-dateutil/dateutil/_common.pyi @@ -1,10 +1,8 @@ -from typing import TypeVar - -_T = TypeVar("_T") +from _typeshed import Self class weekday(object): def __init__(self, weekday: int, n: int | None = ...) -> None: ... - def __call__(self: _T, n: int) -> _T: ... + def __call__(self: Self, n: int) -> Self: ... def __eq__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __hash__(self) -> int: ... diff --git a/stubs/redis/redis/client.pyi b/stubs/redis/redis/client.pyi index 98abd121ed1f..279db79d0068 100644 --- a/stubs/redis/redis/client.pyi +++ b/stubs/redis/redis/client.pyi @@ -680,7 +680,7 @@ class Monitor: command_re: Pattern[str] monitor_re: Pattern[str] def __init__(self, connection_pool) -> None: ... - def __enter__(self) -> Monitor: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def next_command(self) -> dict[str, Any]: ... def listen(self) -> Iterable[dict[str, Any]]: ... diff --git a/stubs/redis/redis/lock.pyi b/stubs/redis/redis/lock.pyi index db8ae5932276..7fad1f11ac79 100644 --- a/stubs/redis/redis/lock.pyi +++ b/stubs/redis/redis/lock.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from typing import Any, ClassVar, Protocol @@ -25,7 +26,7 @@ class Lock: thread_local: bool = ..., ) -> None: ... def register_scripts(self) -> None: ... - def __enter__(self) -> Lock: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... diff --git a/stubs/requests/requests/models.pyi b/stubs/requests/requests/models.pyi index 190125b33c6a..d3d0a4b39e9f 100644 --- a/stubs/requests/requests/models.pyi +++ b/stubs/requests/requests/models.pyi @@ -1,4 +1,5 @@ import datetime +from _typeshed import Self from json import JSONDecoder from typing import Any, Callable, Iterator, Text, TypeVar @@ -106,7 +107,7 @@ class Response: def __bool__(self) -> bool: ... def __nonzero__(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... - def __enter__(self) -> Response: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... @property def next(self) -> PreparedRequest | None: ... diff --git a/stubs/requests/requests/sessions.pyi b/stubs/requests/requests/sessions.pyi index 1250a32836a5..0fe8375da746 100644 --- a/stubs/requests/requests/sessions.pyi +++ b/stubs/requests/requests/sessions.pyi @@ -1,4 +1,4 @@ -from _typeshed import SupportsItems +from _typeshed import Self, SupportsItems from typing import IO, Any, Callable, Iterable, Mapping, MutableMapping, Optional, Text, TypeVar, Union from urllib3 import _collections @@ -62,7 +62,6 @@ _Params = Union[ Union[Text, bytes], ] _TextMapping = MutableMapping[Text, Text] -_SessionT = TypeVar("_SessionT", bound=Session) class Session(SessionRedirectMixin): __attrs__: Any @@ -80,7 +79,7 @@ class Session(SessionRedirectMixin): adapters: MutableMapping[Any, Any] redirect_cache: RecentlyUsedContainer[Any, Any] def __init__(self) -> None: ... - def __enter__(self: _SessionT) -> _SessionT: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args) -> None: ... def prepare_request(self, request: Request) -> PreparedRequest: ... def request(