Use TypeAlias for type aliases where possible, part II (#7667)

This commit is contained in:
Alex Waygood
2022-04-20 20:02:47 +01:00
committed by GitHub
parent c653be73b8
commit b093c90a94
41 changed files with 91 additions and 90 deletions

View File

@@ -1,13 +1,13 @@
import sys
from typing import Any, ClassVar
from typing_extensions import Literal
from typing_extensions import Literal, TypeAlias
PyCF_ONLY_AST: Literal[1024]
if sys.version_info >= (3, 8):
PyCF_TYPE_COMMENTS: Literal[4096]
PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192]
_identifier = str
_identifier: TypeAlias = str
class AST:
if sys.version_info >= (3, 10):
@@ -366,10 +366,10 @@ class Attribute(expr):
ctx: expr_context
if sys.version_info >= (3, 9):
_SliceT = expr
_SliceT: TypeAlias = expr
else:
class slice(AST): ...
_SliceT = slice
_SliceT: TypeAlias = slice
class Slice(_SliceT):
if sys.version_info >= (3, 10):
@@ -524,7 +524,7 @@ if sys.version_info >= (3, 10):
class pattern(AST): ...
# Without the alias, Pyright complains variables named pattern are recursively defined
_pattern = pattern
_pattern: TypeAlias = pattern
class match_case(AST):
__match_args__ = ("pattern", "guard", "body")

View File

@@ -17,7 +17,7 @@ _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: TypeAlias = tuple[Any, ...] | str
_RetAddress = Any
_RetAddress: TypeAlias = Any
# TODO Most methods allow bytes as address objects
# ----- Constants -----

View File

@@ -120,9 +120,9 @@ else:
if sys.platform != "win32":
if sys.version_info >= (3, 7):
_PathType = StrPath
_PathType: TypeAlias = StrPath
else:
_PathType = str
_PathType: TypeAlias = str
if sys.version_info >= (3, 10):
async def open_unix_connection(
path: _PathType | None = ..., *, limit: int = ..., **kwds: Any

View File

@@ -1,6 +1,6 @@
import sys
from _typeshed import Self, SupportsGetItem, SupportsItemAccess
from builtins import type as _type
from builtins import list as _list, type as _type
from collections.abc import Iterable, Iterator, Mapping
from types import TracebackType
from typing import IO, Any, Protocol
@@ -87,8 +87,6 @@ class MiniFieldStorage:
value: Any
def __init__(self, name: Any, value: Any) -> None: ...
_list = list
class FieldStorage:
FieldStorageClass: _type | None
keep_blank_values: int

View File

@@ -36,9 +36,9 @@ _converters: TypeAlias = dict[str, _converter]
_T = TypeVar("_T")
if sys.version_info >= (3, 7):
_Path = StrOrBytesPath
_Path: TypeAlias = StrOrBytesPath
else:
_Path = StrPath
_Path: TypeAlias = StrPath
DEFAULTSECT: Literal["DEFAULT"]
MAX_INTERPOLATION_DEPTH: Literal[10]

View File

@@ -2,7 +2,7 @@ import sys
from _typeshed import Self
from time import struct_time
from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, TypeVar, overload
from typing_extensions import Literal, final
from typing_extensions import Literal, TypeAlias, final
if sys.version_info >= (3, 9):
__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR")
@@ -19,7 +19,7 @@ class tzinfo:
def fromutc(self, __dt: datetime) -> datetime: ...
# Alias required to avoid name conflicts with date(time).tzinfo.
_tzinfo = tzinfo
_tzinfo: TypeAlias = tzinfo
@final
class timezone(tzinfo):
@@ -150,8 +150,8 @@ class time:
fold: int = ...,
) -> Self: ...
_date = date
_time = time
_date: TypeAlias = date
_time: TypeAlias = time
class timedelta(SupportsAbs[timedelta]):
min: ClassVar[timedelta]

View File

@@ -13,7 +13,7 @@ _T = TypeVar("_T")
_PayloadType: TypeAlias = list[Message] | str | bytes
_CharsetType: TypeAlias = Charset | str | None
_HeaderType = Any
_HeaderType: TypeAlias = Any
class Message:
policy: Policy # undocumented

View File

@@ -112,7 +112,7 @@ class partial(Generic[_T]):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
# With protocols, this could change into a generic protocol that defines __get__ and returns _T
_Descriptor = Any
_Descriptor: TypeAlias = Any
class partialmethod(Generic[_T]):
func: Callable[..., _T] | _Descriptor

View File

@@ -514,7 +514,7 @@ def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: .
# Create private type alias to avoid conflict with symbol of same
# name created in Attribute class.
_Object = object
_Object: TypeAlias = object
class Attribute(NamedTuple):
name: str

View File

@@ -1,11 +1,12 @@
from collections.abc import Container, Generator, Iterable, Mapping
from logging import Logger
from typing import Any, ClassVar, NoReturn
from typing_extensions import TypeAlias
from .pgen2.grammar import Grammar
_Driver = Any # really lib2to3.driver.Driver
_BottomMatcher = Any # really lib2to3.btm_matcher.BottomMatcher
_Driver: TypeAlias = Any # really lib2to3.driver.Driver
_BottomMatcher: TypeAlias = Any # really lib2to3.btm_matcher.BottomMatcher
def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = ...) -> list[str]: ...
def get_fixers_from_package(pkg_name: str) -> list[str]: ...

View File

@@ -4,6 +4,7 @@ from collections.abc import Callable, Sequence
from configparser import RawConfigParser
from threading import Thread
from typing import IO, Any, Pattern
from typing_extensions import TypeAlias
from . import _Level
@@ -13,9 +14,9 @@ else:
from typing_extensions import Literal, TypedDict
if sys.version_info >= (3, 7):
_Path = StrOrBytesPath
_Path: TypeAlias = StrOrBytesPath
else:
_Path = StrPath
_Path: TypeAlias = StrPath
DEFAULT_LOGGING_CONFIG_PORT: int
RESET_ERROR: int # undocumented

View File

@@ -7,7 +7,7 @@ from typing_extensions import SupportsIndex, TypeAlias
if sys.version_info >= (3, 8):
_SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex
else:
_SupportsFloatOrIndex = SupportsFloat
_SupportsFloatOrIndex: TypeAlias = SupportsFloat
e: float
pi: float

View File

@@ -2,20 +2,20 @@ import queue
import sys
import threading
from _typeshed import Self
from builtins import dict as _dict, list as _list # Conflicts with method names
from collections.abc import Callable, Iterable, Mapping, Sequence
from types import TracebackType
from typing import Any, AnyStr, Generic, TypeVar
from typing_extensions import TypeAlias
from .connection import Connection
from .context import BaseContext
if sys.version_info >= (3, 8):
from .shared_memory import _SLT, ShareableList, SharedMemory
from .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory
__all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"]
_SharedMemory = SharedMemory
_ShareableList = ShareableList
else:
__all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token"]
@@ -31,7 +31,7 @@ class Namespace:
def __getattr__(self, __name: str) -> Any: ...
def __setattr__(self, __name: str, __value: Any) -> None: ...
_Namespace = Namespace
_Namespace: TypeAlias = Namespace
class Token:
typeid: str | bytes | None
@@ -101,10 +101,6 @@ class BaseManager:
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
) -> None: ...
# Conflicts with method names
_dict = dict
_list = list
class SyncManager(BaseManager):
def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ...
def Condition(self, lock: Any = ...) -> threading.Condition: ...

View File

@@ -3,6 +3,7 @@ import socket
import ssl
import sys
from _typeshed import Self
from builtins import list as _list # conflicts with a method named "list"
from collections.abc import Iterable
from typing import IO, Any, NamedTuple
from typing_extensions import Literal, TypeAlias
@@ -46,8 +47,6 @@ class ArticleInfo(NamedTuple):
def decode_header(header_str: str) -> str: ...
_list = list # conflicts with a method named "list"
class NNTP:
encoding: str
errors: str

View File

@@ -1,5 +1,6 @@
import socket
import ssl
from builtins import list as _list # conflicts with a method named "list"
from typing import Any, BinaryIO, NoReturn, Pattern, overload
from typing_extensions import Literal, TypeAlias
@@ -16,8 +17,6 @@ LF: Literal[b"\n"]
CRLF: Literal[b"\r\n"]
HAVE_SSL: bool
_list = list # conflicts with a method named "list"
class POP3:
encoding: str
host: str

View File

@@ -1,5 +1,6 @@
from _typeshed import SupportsWrite
from abc import abstractmethod
from builtins import list as _list # "list" conflicts with method name
from collections.abc import Callable, Container, Mapping, MutableMapping
from reprlib import Repr
from types import MethodType, ModuleType, TracebackType
@@ -197,8 +198,6 @@ def doc(thing: str | object, title: str = ..., forceload: bool = ..., output: Su
def writedoc(thing: str | object, forceload: bool = ...) -> None: ...
def writedocs(dir: str, pkgpath: str = ..., done: Any | None = ...) -> None: ...
_list = list # "list" conflicts with method name
class Helper:
keywords: dict[str, str | tuple[str, str]]
symbols: dict[str, str]

View File

@@ -3,8 +3,9 @@ from _typeshed import FileDescriptor, FileDescriptorLike, Self
from abc import ABCMeta, abstractmethod
from collections.abc import Mapping
from typing import Any, NamedTuple
from typing_extensions import TypeAlias
_EventMask = int
_EventMask: TypeAlias = int
EVENT_READ: _EventMask
EVENT_WRITE: _EventMask

View File

@@ -38,7 +38,7 @@ _StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath)
_StrPathT = TypeVar("_StrPathT", bound=StrPath)
# Return value of some functions that may either return a path-like object that was passed in or
# a string
_PathReturn = Any
_PathReturn: TypeAlias = Any
class Error(OSError): ...
class SameFileError(Error): ...

View File

@@ -2,7 +2,7 @@ import bz2
import io
import sys
from _typeshed import Self, StrOrBytesPath, StrPath
from builtins import type as Type # alias to avoid name clashes with fields named "type"
from builtins import list as _list, type as Type # aliases to avoid name clashes with fields named "type" or "list"
from collections.abc import Callable, Iterable, Iterator, Mapping
from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj
from types import TracebackType
@@ -109,8 +109,6 @@ def open(
class ExFileObject(io.BufferedReader):
def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ...
_list = list # conflicts with method name
class TarFile:
OPEN_METH: Mapping[str, str]
name: StrOrBytesPath | None

View File

@@ -134,7 +134,7 @@ __all__ = [
# same, but as per the "no union returns" typeshed policy, we'll return
# Any instead.
_Color: TypeAlias = Union[str, tuple[float, float, float]]
_AnyColor = Any
_AnyColor: TypeAlias = Any
# TODO: Replace this with a TypedDict once it becomes standardized.
_PenState: TypeAlias = dict[str, Any]

View File

@@ -286,7 +286,7 @@ class _patch_dict:
if sys.version_info >= (3, 8):
_Mock: TypeAlias = MagicMock | AsyncMock
else:
_Mock = MagicMock
_Mock: TypeAlias = MagicMock
class _patcher:
TEST_PREFIX: str

View File

@@ -2,8 +2,9 @@ from collections.abc import Callable, Iterable
from datetime import timedelta
from logging import Logger
from typing import Any
from typing_extensions import TypeAlias
_App = Any # flask is not part of typeshed
_App: TypeAlias = Any # flask is not part of typeshed
LOG: Logger

View File

@@ -1,8 +1,9 @@
from _typeshed import Self
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
from typing import Any, overload
from typing_extensions import TypeAlias
_NDArray = Any # FIXME: no typings for numpy arrays
_NDArray: TypeAlias = Any # FIXME: no typings for numpy arrays
class _JackPositionT: ...

View File

@@ -1,5 +1,6 @@
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from typing import Any, Pattern, TypeVar, overload
from typing_extensions import TypeAlias
from . import resolver as resolver # Help mypy a bit; this is implied by loader and dumper
from .constructor import BaseConstructor
@@ -16,7 +17,7 @@ from .resolver import BaseResolver
from .tokens import *
# FIXME: the functions really return str if encoding is None, otherwise bytes. Waiting for python/mypy#5621
_Yaml = Any
_Yaml: TypeAlias = Any
__with_libyaml__: Any
__version__: str

View File

@@ -14,7 +14,7 @@ INVISIBLE_CHARACTERS_RE: Pattern[str]
INVISIBLE_REPLACEMENT_CHAR: str
# A html5lib Filter class
_Filter = Any
_Filter: TypeAlias = Any
class Cleaner:
tags: Container[str]

View File

@@ -118,7 +118,7 @@ class LRUCache(dict[_KT, _VT]):
def __init__(self, capacity: int) -> None: ...
# This exists to work around Password.str's name shadowing the str type
_str = str
_str: TypeAlias = str
class Password:
hashfunc: Callable[[bytes], _HashType]

View File

@@ -1,5 +1,6 @@
from collections.abc import Iterable, Mapping
from typing import Any
from typing_extensions import TypeAlias
from urllib.parse import ParseResult, SplitResult
from requests.auth import AuthBase
@@ -9,7 +10,7 @@ from requests.structures import CaseInsensitiveDict
from .lib.url import URL
from .objects import Calendar, DAVObject, Principal
_Element = Any # actually lxml.etree._Element
_Element: TypeAlias = Any # actually lxml.etree._Element
class DAVResponse:
reason: str

View File

@@ -1,8 +1,9 @@
from _typeshed import Self
from collections.abc import Iterable
from typing import Any, ClassVar
from typing_extensions import TypeAlias
_Element = Any # actually lxml.etree._Element
_Element: TypeAlias = Any # actually lxml.etree._Element
class BaseElement:
tag: ClassVar[str | None]

View File

@@ -2,7 +2,7 @@ import datetime
from _typeshed import Self
from collections.abc import Iterable, Iterator, Mapping
from typing import Any, TypeVar, overload
from typing_extensions import Literal
from typing_extensions import Literal, TypeAlias
from urllib.parse import ParseResult, SplitResult
from vobject.base import VBase
@@ -13,7 +13,7 @@ from .lib.url import URL
_CC = TypeVar("_CC", bound=CalendarObjectResource)
_vCalAddress = Any # actually icalendar.vCalAddress
_vCalAddress: TypeAlias = Any # actually icalendar.vCalAddress
class DAVObject:
id: str | None

View File

@@ -1,4 +1,5 @@
import sys
from builtins import dict as _dict # alias to avoid conflicts with attribute name
from collections.abc import Callable, Iterator
from typing import Any, NamedTuple, Pattern, TypeVar
from typing_extensions import ParamSpec
@@ -31,8 +32,6 @@ else:
DEF: Pattern[str]
_dict = dict # conflicts with attribute name
class FunctionMaker:
args: list[str]
varargs: str | None

View File

@@ -1,4 +1,5 @@
import optparse
from builtins import list as _list # alias to avoid name clashes with fields named list
from collections.abc import Iterable
from typing import Any
from typing_extensions import Literal, TypeAlias
@@ -7,8 +8,6 @@ from docutils import ApplicationError
from docutils.io import FileOutput
from docutils.nodes import document
_list = list
class DependencyList:
list: _list[str]
file: FileOutput | None

View File

@@ -182,7 +182,7 @@ class _Parser:
def ParseLines(self, lines: Iterable[Text | bytes], message: _M) -> _M: ...
def MergeLines(self, lines: Iterable[Text | bytes], message: _M) -> _M: ...
_ParseError = ParseError
_ParseError: TypeAlias = ParseError
class Tokenizer:
token: str = ...

View File

@@ -275,7 +275,7 @@ class Xid:
def __getitem__(self, __index): ...
def __len__(self): ...
_cursor = cursor
_cursor: TypeAlias = cursor
_T_cur = TypeVar("_T_cur", bound=_cursor)
class connection:

View File

@@ -159,32 +159,32 @@ def in_string_annotation(func: _F) -> _F: ...
def make_tokens(code: str | bytes) -> tuple[TokenInfo, ...]: ...
if sys.version_info >= (3, 8):
_NamedExpr = ast.NamedExpr
_NamedExpr: TypeAlias = ast.NamedExpr
else:
_NamedExpr = Any
_NamedExpr: TypeAlias = Any
if sys.version_info >= (3, 10):
_Match = ast.Match
_MatchCase = ast.match_case
_MatchValue = ast.MatchValue
_MatchSingleton = ast.MatchSingleton
_MatchSequence = ast.MatchSequence
_MatchStar = ast.MatchStar
_MatchMapping = ast.MatchMapping
_MatchClass = ast.MatchClass
_MatchAs = ast.MatchAs
_MatchOr = ast.MatchOr
_Match: TypeAlias = ast.Match
_MatchCase: TypeAlias = ast.match_case
_MatchValue: TypeAlias = ast.MatchValue
_MatchSingleton: TypeAlias = ast.MatchSingleton
_MatchSequence: TypeAlias = ast.MatchSequence
_MatchStar: TypeAlias = ast.MatchStar
_MatchMapping: TypeAlias = ast.MatchMapping
_MatchClass: TypeAlias = ast.MatchClass
_MatchAs: TypeAlias = ast.MatchAs
_MatchOr: TypeAlias = ast.MatchOr
else:
_Match = Any
_MatchCase = Any
_MatchValue = Any
_MatchSingleton = Any
_MatchSequence = Any
_MatchStar = Any
_MatchMapping = Any
_MatchClass = Any
_MatchAs = Any
_MatchOr = Any
_Match: TypeAlias = Any
_MatchCase: TypeAlias = Any
_MatchValue: TypeAlias = Any
_MatchSingleton: TypeAlias = Any
_MatchSequence: TypeAlias = Any
_MatchStar: TypeAlias = Any
_MatchMapping: TypeAlias = Any
_MatchClass: TypeAlias = Any
_MatchAs: TypeAlias = Any
_MatchOr: TypeAlias = Any
class Checker:
nodeDepth: int

View File

@@ -1,6 +1,7 @@
from _typeshed import Self
from datetime import date, datetime, timedelta
from typing import SupportsFloat, TypeVar, overload
from typing_extensions import TypeAlias
from ._common import weekday
@@ -8,7 +9,7 @@ from ._common import weekday
_SelfT = TypeVar("_SelfT", bound=relativedelta)
_DateT = TypeVar("_DateT", date, datetime)
# Work around attribute and type having the same name.
_weekday = weekday
_weekday: TypeAlias = weekday
MO: weekday
TU: weekday

View File

@@ -1,5 +1,6 @@
import datetime
from typing import Any, Iterable
from typing_extensions import TypeAlias
from ._common import weekday as weekdaybase
@@ -81,7 +82,7 @@ class _iterinfo:
def mtimeset(self, hour, minute, second): ...
def stimeset(self, hour, minute, second): ...
_rrule = rrule
_rrule: TypeAlias = rrule
class rruleset(rrulebase):
class _genitem:

View File

@@ -1,6 +1,7 @@
from _typeshed import Self
from collections.abc import Mapping
from typing import Any
from typing_extensions import TypeAlias
from .retry import Retry
@@ -12,7 +13,7 @@ SYM_EMPTY: Any
SERVER_CLOSED_CONNECTION_ERROR: Any
# Options as passed to Pool.get_connection().
_ConnectionPoolOptions = Any
_ConnectionPoolOptions: TypeAlias = Any
class BaseParser:
EXCEPTION_CLASSES: Any

View File

@@ -9,7 +9,7 @@ from . import adapters, auth as _auth, compat, cookies, exceptions, hooks, model
from .models import Response
from .structures import CaseInsensitiveDict as CaseInsensitiveDict
_BaseAdapter = adapters.BaseAdapter
_BaseAdapter: TypeAlias = adapters.BaseAdapter
OrderedDict = compat.OrderedDict
cookiejar_from_dict = cookies.cookiejar_from_dict
extract_cookies_to_jar = cookies.extract_cookies_to_jar

View File

@@ -1,5 +1,6 @@
from collections.abc import Iterator
from typing import Any
from typing_extensions import TypeAlias
class NodeVisitor:
def visit(self, node: AST) -> Any: ...
@@ -152,7 +153,7 @@ class Break(stmt): ...
class Continue(stmt): ...
class slice(AST): ...
_slice = slice # this lets us type the variable named 'slice' below
_slice: TypeAlias = slice # this lets us type the variable named 'slice' below
class Slice(slice):
lower: expr | None

View File

@@ -1,5 +1,6 @@
from collections.abc import Iterator
from typing import Any
from typing_extensions import TypeAlias
class NodeVisitor:
def visit(self, node: AST) -> Any: ...
@@ -168,7 +169,7 @@ class Break(stmt): ...
class Continue(stmt): ...
class slice(AST): ...
_slice = slice # this lets us type the variable named 'slice' below
_slice: TypeAlias = slice # this lets us type the variable named 'slice' below
class Slice(slice):
lower: expr | None

View File

@@ -3,10 +3,11 @@ from io import BytesIO
from logging import Logger
from socket import socket
from typing import Any
from typing_extensions import TypeAlias
from . import compat as compat, utilities as utilities
_socket = socket
_socket: TypeAlias = socket
socket_map: Mapping[int, socket]
map: Mapping[int, socket]