Skip to content

Use TypeAlias where possible for type aliases #7630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions stdlib/_codecs.pyi
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import codecs
import sys
from typing import Any, Callable
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: ...
Expand Down
4 changes: 2 additions & 2 deletions stdlib/_csv.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Any, Iterable, Iterator, Protocol, Union
from typing_extensions import Literal
from typing_extensions import Literal, TypeAlias

__version__: str

Expand All @@ -21,7 +21,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
Expand Down
4 changes: 2 additions & 2 deletions stdlib/_curses.pyi
Original file line number Diff line number Diff line change
@@ -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
Expand Down
5 changes: 3 additions & 2 deletions stdlib/_dummy_threading.pyi
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import sys
from types import FrameType, TracebackType
from typing import Any, Callable, Iterable, Mapping, 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):
Expand Down
4 changes: 2 additions & 2 deletions stdlib/_operator.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ from typing import (
TypeVar,
overload,
)
from typing_extensions import ParamSpec, SupportsIndex, final
from typing_extensions import ParamSpec, SupportsIndex, TypeAlias, final

_R = TypeVar("_R")
_T = TypeVar("_T")
Expand All @@ -40,7 +40,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: ...
Expand Down
4 changes: 3 additions & 1 deletion stdlib/_random.pyi
Original file line number Diff line number Diff line change
@@ -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: ...
Expand Down
11 changes: 6 additions & 5 deletions stdlib/_socket.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@ 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
_Address: TypeAlias = tuple[Any, ...] | str
_RetAddress = Any
# TODO Most methods allow bytes as address objects

Expand Down
3 changes: 2 additions & 1 deletion stdlib/_threading_local.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
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
Expand Down
2 changes: 1 addition & 1 deletion stdlib/_typeshed/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,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+",
Expand Down
6 changes: 3 additions & 3 deletions stdlib/aifc.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -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: ...
Expand Down
10 changes: 5 additions & 5 deletions stdlib/array.pyi
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import sys
from _typeshed import Self
from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, overload
from typing_extensions import Literal, SupportsIndex
from typing_extensions import Literal, SupportsIndex, TypeAlias

_IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"]
_FloatTypeCode = Literal["f", "d"]
_UnicodeTypeCode = Literal["u"]
_TypeCode = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode
_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)

Expand Down
10 changes: 5 additions & 5 deletions stdlib/asyncio/base_events.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ from asyncio.transports import BaseTransport, ReadTransport, SubprocessTransport
from collections.abc import Iterable
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_extensions import Literal, TypeAlias

if sys.version_info >= (3, 7):
from contextvars import Context
Expand All @@ -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):
Expand Down
3 changes: 2 additions & 1 deletion stdlib/asyncio/base_subprocess.pyi
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import subprocess
from collections import deque
from typing import IO, Any, Callable, Sequence
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):

Expand Down
10 changes: 5 additions & 5 deletions stdlib/asyncio/events.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ from _typeshed import FileDescriptorLike, Self
from abc import ABCMeta, abstractmethod
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_extensions import Literal, TypeAlias

from .base_events import Server
from .futures import Future
Expand Down Expand Up @@ -75,10 +75,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
Expand Down
3 changes: 2 additions & 1 deletion stdlib/asyncio/format_helpers.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import functools
import traceback
from types import FrameType, FunctionType
from typing import Any, Iterable, 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]: ...
Expand Down
3 changes: 2 additions & 1 deletion stdlib/asyncio/streams.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sys
from _typeshed import Self, StrPath
from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Sequence
from typing_extensions import TypeAlias

from . import events, protocols, transports
from .base_events import Server
Expand Down Expand Up @@ -64,7 +65,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):
Expand Down
6 changes: 3 additions & 3 deletions stdlib/asyncio/subprocess.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ 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 typing_extensions import Literal, TypeAlias

if sys.version_info >= (3, 7):
__all__ = ("create_subprocess_exec", "create_subprocess_shell")
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
Expand Down
6 changes: 3 additions & 3 deletions stdlib/asyncio/tasks.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import sys
from collections.abc import Awaitable, Generator, Iterable, Iterator
from types import FrameType
from typing import Any, Coroutine, Generic, TextIO, TypeVar, overload
from typing_extensions import Literal
from typing_extensions import Literal, TypeAlias

from .events import AbstractEventLoop
from .futures import Future
Expand Down Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions stdlib/asyncio/trsock.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import sys
from builtins import type as Type # alias to avoid name clashes with property named "type"
from types import TracebackType
from typing import Any, BinaryIO, Iterable, 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: ...
Expand Down
5 changes: 3 additions & 2 deletions stdlib/asyncore.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 4 additions & 2 deletions stdlib/audioop.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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): ...

Expand Down
6 changes: 3 additions & 3 deletions stdlib/bdb.pyi
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from types import CodeType, FrameType, TracebackType
from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, TypeVar
from typing_extensions import Literal, ParamSpec
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
_ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, FrameType]

GENERATOR_AND_COROUTINE_FLAGS: Literal[672]

Expand Down
6 changes: 3 additions & 3 deletions stdlib/binhex.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import IO, Any
from typing_extensions import Literal
from typing_extensions import Literal, TypeAlias

__all__ = ["binhex", "hexbin", "Error"]

Expand All @@ -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: ...

Expand Down
Loading