Skip to content

Commit

Permalink
Add TypeAlias annotations to mypy code (#11321)
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn committed Oct 14, 2021
1 parent d3fe55a commit f497645
Show file tree
Hide file tree
Showing 14 changed files with 58 additions and 49 deletions.
4 changes: 2 additions & 2 deletions mypy/binder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from collections import defaultdict

from typing import Dict, List, Set, Iterator, Union, Optional, Tuple, cast
from typing_extensions import DefaultDict
from typing_extensions import DefaultDict, TypeAlias as _TypeAlias

from mypy.types import (
Type, AnyType, PartialType, UnionType, TypeOfAny, NoneType, get_proper_type
Expand All @@ -16,7 +16,7 @@
from mypy.nodes import IndexExpr, MemberExpr, AssignmentExpr, NameExpr


BindableExpression = Union[IndexExpr, MemberExpr, AssignmentExpr, NameExpr]
BindableExpression: _TypeAlias = Union[IndexExpr, MemberExpr, AssignmentExpr, NameExpr]


class Frame:
Expand Down
4 changes: 2 additions & 2 deletions mypy/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from typing import (AbstractSet, Any, Dict, Iterable, Iterator, List, Sequence,
Mapping, NamedTuple, Optional, Set, Tuple, TypeVar, Union, Callable, TextIO)
from typing_extensions import ClassVar, Final, TYPE_CHECKING
from typing_extensions import ClassVar, Final, TYPE_CHECKING, TypeAlias as _TypeAlias
from mypy_extensions import TypedDict

from mypy.nodes import MypyFile, ImportBase, Import, ImportFrom, ImportAll, SymbolTable
Expand Down Expand Up @@ -81,7 +81,7 @@
}


Graph = Dict[str, 'State']
Graph: _TypeAlias = Dict[str, 'State']


# TODO: Get rid of BuildResult. We might as well return a BuildManager.
Expand Down
8 changes: 4 additions & 4 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
Any, Dict, Set, List, cast, Tuple, TypeVar, Union, Optional, NamedTuple, Iterator,
Iterable, Sequence, Mapping, Generic, AbstractSet, Callable
)
from typing_extensions import Final
from typing_extensions import Final, TypeAlias as _TypeAlias

from mypy.backports import nullcontext
from mypy.errors import Errors, report_internal_error
Expand Down Expand Up @@ -86,8 +86,8 @@

DEFAULT_LAST_PASS: Final = 1 # Pass numbers start at 0

DeferredNodeType = Union[FuncDef, LambdaExpr, OverloadedFuncDef, Decorator]
FineGrainedDeferredNodeType = Union[FuncDef, MypyFile, OverloadedFuncDef]
DeferredNodeType: _TypeAlias = Union[FuncDef, LambdaExpr, OverloadedFuncDef, Decorator]
FineGrainedDeferredNodeType: _TypeAlias = Union[FuncDef, MypyFile, OverloadedFuncDef]

# A node which is postponed to be processed during the next pass.
# In normal mode one can defer functions and methods (also decorated and/or overloaded)
Expand Down Expand Up @@ -124,7 +124,7 @@
# probably be better to have the dict keyed by the nodes' literal_hash
# field instead.

TypeMap = Optional[Dict[Expression, Type]]
TypeMap: _TypeAlias = Optional[Dict[Expression, Type]]

# An object that represents either a precise type or a type with an upper bound;
# it is important for correct type inference with isinstance.
Expand Down
29 changes: 16 additions & 13 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import (
Any, cast, Dict, Set, List, Tuple, Callable, Union, Optional, Sequence, Iterator
)
from typing_extensions import ClassVar, Final, overload
from typing_extensions import ClassVar, Final, overload, TypeAlias as _TypeAlias

from mypy.errors import report_internal_error
from mypy.typeanal import (
Expand Down Expand Up @@ -72,18 +72,21 @@

# Type of callback user for checking individual function arguments. See
# check_args() below for details.
ArgChecker = Callable[[Type,
Type,
ArgKind,
Type,
int,
int,
CallableType,
Optional[Type],
Context,
Context,
MessageBuilder],
None]
ArgChecker: _TypeAlias = Callable[[
Type,
Type,
ArgKind,
Type,
int,
int,
CallableType,
Optional[Type],
Context,
Context,
MessageBuilder,
],
None,
]

# Maximum nesting level for math union in overloads, setting this to large values
# may cause performance issues. The reason is that although union math algorithm we use
Expand Down
8 changes: 4 additions & 4 deletions mypy/checkstrformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from typing import (
cast, List, Tuple, Dict, Callable, Union, Optional, Pattern, Match, Set
)
from typing_extensions import Final, TYPE_CHECKING
from typing_extensions import Final, TYPE_CHECKING, TypeAlias as _TypeAlias

from mypy.types import (
Type, AnyType, TupleType, Instance, UnionType, TypeOfAny, get_proper_type, TypeVarType,
Expand All @@ -39,9 +39,9 @@
from mypy.subtypes import is_subtype
from mypy.parse import parse

FormatStringExpr = Union[StrExpr, BytesExpr, UnicodeExpr]
Checkers = Tuple[Callable[[Expression], None], Callable[[Type], bool]]
MatchMap = Dict[Tuple[int, int], Match[str]] # span -> match
FormatStringExpr: _TypeAlias = Union[StrExpr, BytesExpr, UnicodeExpr]
Checkers: _TypeAlias = Tuple[Callable[[Expression], None], Callable[[Type], bool]]
MatchMap: _TypeAlias = Dict[Tuple[int, int], Match[str]] # span -> match


def compile_format_re() -> Pattern[str]:
Expand Down
8 changes: 5 additions & 3 deletions mypy/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
import tomli
from typing import (Any, Callable, Dict, List, Mapping, MutableMapping, Optional, Sequence,
TextIO, Tuple, Union)
from typing_extensions import Final
from typing_extensions import Final, TypeAlias as _TypeAlias

from mypy import defaults
from mypy.options import Options, PER_MODULE_OPTIONS

_CONFIG_VALUE_TYPES = Union[str, bool, int, float, Dict[str, str], List[str], Tuple[int, int]]
_INI_PARSER_CALLABLE = Callable[[Any], _CONFIG_VALUE_TYPES]
_CONFIG_VALUE_TYPES: _TypeAlias = Union[
str, bool, int, float, Dict[str, str], List[str], Tuple[int, int],
]
_INI_PARSER_CALLABLE: _TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]


def parse_version(v: str) -> Tuple[int, int]:
Expand Down
10 changes: 5 additions & 5 deletions mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from typing import (
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional, Callable, Sequence, Iterator
)
from typing_extensions import DefaultDict, Final, TYPE_CHECKING
from typing_extensions import DefaultDict, Final, TYPE_CHECKING, TypeAlias as _TypeAlias
from mypy_extensions import trait

import mypy.strconv
Expand Down Expand Up @@ -64,7 +64,7 @@ def get_column(self) -> int:

T = TypeVar('T')

JsonDict = Dict[str, Any]
JsonDict: _TypeAlias = Dict[str, Any]


# Symbol table node kinds
Expand Down Expand Up @@ -208,7 +208,7 @@ class FakeExpression(Expression):
# TODO:
# Lvalue = Union['NameExpr', 'MemberExpr', 'IndexExpr', 'SuperExpr', 'StarExpr'
# 'TupleExpr']; see #1783.
Lvalue = Expression
Lvalue: _TypeAlias = Expression


@trait
Expand Down Expand Up @@ -241,7 +241,7 @@ def deserialize(cls, data: JsonDict) -> 'SymbolNode':


# Items: fullname, related symbol table node, surrounding type (if any)
Definition = Tuple[str, 'SymbolTableNode', Optional['TypeInfo']]
Definition: _TypeAlias = Tuple[str, 'SymbolTableNode', Optional['TypeInfo']]


class MypyFile(SymbolNode):
Expand Down Expand Up @@ -514,7 +514,7 @@ def fullname(self) -> Bogus[str]:
return self._fullname


OverloadPart = Union['FuncDef', 'Decorator']
OverloadPart: _TypeAlias = Union['FuncDef', 'Decorator']


class OverloadedFuncDef(FuncBase, SymbolNode, Statement):
Expand Down
7 changes: 5 additions & 2 deletions mypy/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import typing
from typing import Any, Callable, Dict, List, Optional, Tuple, cast, Iterator
from typing_extensions import Final
from typing_extensions import Final, TypeAlias as _TypeAlias

from mypy.nodes import MypyFile, Expression, FuncDef
from mypy import stats
Expand Down Expand Up @@ -45,7 +45,10 @@
]
)

ReporterClasses = Dict[str, Tuple[Callable[['Reports', str], 'AbstractReporter'], bool]]
ReporterClasses: _TypeAlias = Dict[
str,
Tuple[Callable[['Reports', str], 'AbstractReporter'], bool],
]

reporter_classes: Final[ReporterClasses] = {}

Expand Down
3 changes: 2 additions & 1 deletion mypy/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@

from contextlib import contextmanager
from typing import List, Optional, Iterator, Tuple
from typing_extensions import TypeAlias as _TypeAlias

from mypy.backports import nullcontext
from mypy.nodes import TypeInfo, FuncBase


SavedScope = Tuple[str, Optional[TypeInfo], Optional[FuncBase]]
SavedScope: _TypeAlias = Tuple[str, Optional[TypeInfo], Optional[FuncBase]]


class Scope:
Expand Down
4 changes: 2 additions & 2 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
from typing import (
List, Dict, Set, Tuple, cast, TypeVar, Union, Optional, Callable, Iterator, Iterable
)
from typing_extensions import Final
from typing_extensions import Final, TypeAlias as _TypeAlias

from mypy.nodes import (
MypyFile, TypeInfo, Node, AssignmentStmt, FuncDef, OverloadedFuncDef,
Expand Down Expand Up @@ -147,7 +147,7 @@


# Used for tracking incomplete references
Tag = int
Tag: _TypeAlias = int


class SemanticAnalyzer(NodeVisitor[None],
Expand Down
4 changes: 2 additions & 2 deletions mypy/semanal_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"""

from typing import List, Tuple, Optional, Union, Callable
from typing_extensions import TYPE_CHECKING, Final
from typing_extensions import TYPE_CHECKING, Final, TypeAlias as _TypeAlias

from mypy.backports import nullcontext
from mypy.nodes import (
Expand All @@ -51,7 +51,7 @@
from mypy.build import Graph, State


Patches = List[Tuple[int, Callable[[], None]]]
Patches: _TypeAlias = List[Tuple[int, Callable[[], None]]]


# If we perform this many iterations, raise an exception since we are likely stuck.
Expand Down
4 changes: 2 additions & 2 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from contextlib import contextmanager

from typing import Any, List, Optional, Callable, Tuple, Iterator, Set, Union, cast, TypeVar
from typing_extensions import Final
from typing_extensions import Final, TypeAlias as _TypeAlias

from mypy.types import (
Type, AnyType, UnboundType, TypeVisitor, FormalArgument, NoneType,
Expand Down Expand Up @@ -30,7 +30,7 @@
IS_CLASSVAR: Final = 2
IS_CLASS_OR_STATIC: Final = 3

TypeParameterChecker = Callable[[Type, Type, int], bool]
TypeParameterChecker: _TypeAlias = Callable[[Type, Type, int], bool]


def check_type_parameter(lefta: Type, righta: Type, variance: int) -> bool:
Expand Down
6 changes: 3 additions & 3 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple,
Sequence, Iterator
)
from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload
from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias

import mypy.nodes
from mypy import state
Expand All @@ -23,7 +23,7 @@

T = TypeVar('T')

JsonDict = Dict[str, Any]
JsonDict: _TypeAlias = Dict[str, Any]

# The set of all valid expressions that can currently be contained
# inside of a Literal[...].
Expand Down Expand Up @@ -52,7 +52,7 @@
# Note: Although "Literal[None]" is a valid type, we internally always convert
# such a type directly into "None". So, "None" is not a valid parameter of
# LiteralType and is omitted from this list.
LiteralValue = Union[int, str, bool]
LiteralValue: _TypeAlias = Union[int, str, bool]


# If we only import type_visitor in the middle of the file, mypy
Expand Down
8 changes: 4 additions & 4 deletions mypy/typestate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,23 @@
"""

from typing import Dict, Set, Tuple, Optional, List
from typing_extensions import ClassVar, Final
from typing_extensions import ClassVar, Final, TypeAlias as _TypeAlias

from mypy.nodes import TypeInfo
from mypy.types import Instance, TypeAliasType, get_proper_type, Type
from mypy.server.trigger import make_trigger
from mypy import state

# Represents that the 'left' instance is a subtype of the 'right' instance
SubtypeRelationship = Tuple[Instance, Instance]
SubtypeRelationship: _TypeAlias = Tuple[Instance, Instance]

# A tuple encoding the specific conditions under which we performed the subtype check.
# (e.g. did we want a proper subtype? A regular subtype while ignoring variance?)
SubtypeKind = Tuple[bool, ...]
SubtypeKind: _TypeAlias = Tuple[bool, ...]

# A cache that keeps track of whether the given TypeInfo is a part of a particular
# subtype relationship
SubtypeCache = Dict[TypeInfo, Dict[SubtypeKind, Set[SubtypeRelationship]]]
SubtypeCache: _TypeAlias = Dict[TypeInfo, Dict[SubtypeKind, Set[SubtypeRelationship]]]


class TypeState:
Expand Down

0 comments on commit f497645

Please sign in to comment.