8000 Microrefactoring: use more constants for type names (#11803) · python/mypy@6ea7cfa · GitHub
[go: up one dir, main page]

Skip to content

Commit 6ea7cfa

Browse files
Microrefactoring: use more constants for type names (#11803)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 25b2129 commit 6ea7cfa

File tree

5 files changed

+58
-31
lines changed

5 files changed

+58
-31
lines changed

mypy/checkexpr.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
PartialType, DeletedType, UninhabitedType, TypeType, TypeOfAny, LiteralType, LiteralValue,
2121
is_named_instance, FunctionLike, ParamSpecType, ParamSpecFlavor,
2222
StarType, is_optional, remove_optional, is_generic_instance, get_proper_type, ProperType,
23-
get_proper_types, flatten_nested_unions
23+
get_proper_types, flatten_nested_unions, LITERAL_TYPE_NAMES,
2424
)
2525
from mypy.nodes import (
2626
NameExpr, RefExpr, Var, FuncDef, OverloadedFuncDef, TypeInfo, CallExpr,
@@ -4551,10 +4551,9 @@ def try_getting_literal(typ: Type) -> ProperType:
45514551

45524552
def is_expr_literal_type(node: Expression) -> bool:
45534553
"""Returns 'true' if the given node is a Literal"""
4554-
valid = ('typing.Literal', 'typing_extensions.Literal')
45554554
if isinstance(node, IndexExpr):
45564555
base = node.base
4557-
return isinstance(base, RefExpr) and base.fullname in valid
4556+
return isinstance(base, RefExpr) and base.fullname in LITERAL_TYPE_NAMES
45584557
if isinstance(node, NameExpr):
45594558
underlying = node.node
45604559
return isinstance(underlying, TypeAlias) and isinstance(get_proper_type(underlying.target),

mypy/exprtotype.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from mypy.fastparse import parse_type_string
1111
from mypy.types import (
1212
Type, UnboundType, TypeList, EllipsisType, AnyType, CallableArgument, TypeOfAny,
13-
RawExpressionType, ProperType, UnionType
13+
RawExpressionType, ProperType, UnionType, ANNOTATED_TYPE_NAMES,
1414
)
1515
from mypy.options import Options
1616

@@ -69,9 +69,7 @@ def expr_to_unanalyzed_type(expr: Expression,
6969
else:
7070
args = [expr.index]
7171

72-
if isinstance(expr.base, RefExpr) and expr.base.fullname in [
73-
'typing.Annotated', 'typing_extensions.Annotated'
74-
]:
72+
if isinstance(expr.base, RefExpr) and expr.base.fullname in ANNOTATED_TYPE_NAMES:
7573
# TODO: this is not the optimal solution as we are basically getting rid
7674
# of the Annotation definition and only returning the type information,
7775
# losing all the annotations.

mypy/semanal.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@
9292
FunctionLike, UnboundType, TypeVarType, TupleType, UnionType, StarType,
9393
CallableType, Overloaded, Instance, Type, AnyType, LiteralType, LiteralValue,
9494
TypeTranslator, TypeOfAny, TypeType, NoneType, PlaceholderType, TPDICT_NAMES, ProperType,
95-
get_proper_type, get_proper_types, TypeAliasType, TypeVarLikeType
95+
get_proper_type, get_proper_types, TypeAliasType, TypeVarLikeType,
96+
PROTOCOL_NAMES, TYPE_ALIAS_NAMES, FINAL_TYPE_NAMES, FINAL_DECORATOR_NAMES,
9697
)
9798
from mypy.typeops import function_type, get_type_vars
9899
from mypy.type_visitor import TypeQuery
@@ -1154,8 +1155,7 @@ def analyze_class(self, defn: ClassDef) -> None:
11541155
for decorator in defn.decorators:
11551156
decorator.accept(self)
11561157
if isinstance(decorator, RefExpr):
1157-
if decorator.fullname in ('typing.final',
1158-
'typing_extensions.final'):
1158+
if decorator.fullname in FINAL_DECORATOR_NAMES:
11591159
self.fail("@final cannot be used with TypedDict", decorator)
11601160
if info is None:
11611161
self.mark_incomplete(defn.name, defn)
@@ -1282,8 +1282,7 @@ def analyze_class_decorator(self, defn: ClassDef, decorator: Expression) -> None
12821282
else:
12831283
self.fail('@runtime_checkable can only be used with protocol classes',
12841284
defn)
1285-
elif decorator.fullname in ('typing.final',
1286-
'typing_extensions.final'):
1285+
elif decorator.fullname in FINAL_DECORATOR_NAMES:
12871286
defn.info.is_final = True
12881287

12891288
def clean_up_bases_and_infer_type_variables(
@@ -1328,8 +1327,7 @@ class Foo(Bar, Generic[T]): ...
13281327
if isinstance(base, UnboundType):
13291328
sym = self.lookup_qualified(base.name, base)
13301329
if sym is not None and sym.node is not None:
1331-
if (sym.node.fullname in ('typing.Protocol', 'typing_extensions.Protocol') and
1332-
i not in removed):
1330+
if sym.node.fullname in PROTOCOL_NAMES and i not in removed:
13331331
# also remove bare 'Protocol' bases
13341332
removed.append(i)
13351333
is_protocol = True
@@ -1377,8 +1375,7 @@ def analyze_class_typevar_declaration(
13771375
if sym is None or sym.node is None:
13781376
return None
13791377
if (sym.node.fullname == 'typing.Generic' or
1380-
sym.node.fullname == 'typing.Protocol' and base.args or
1381-
sym.node.fullname == 'typing_extensions.Protocol' and base.args):
1378+
sym.node.fullname in PROTOCOL_NAMES and base.args):
13821379
is_proto = sym.node.fullname != 'typing.Generic'
13831380
tvars: TypeVarLikeList = []
13841381
for arg in unbound.args:
@@ -2669,7 +2666,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:
26692666
pep_613 = False
26702667
if s.unanalyzed_type is not None and isinstance(s.unanalyzed_type, UnboundType):
26712668
lookup = self.lookup(s.unanalyzed_type.name, s, suppress_errors=True)
2672-
if lookup and lookup.fullname in ("typing.TypeAlias", "typing_extensions.TypeAlias"):
2669+
if lookup and lookup.fullname in TYPE_ALIAS_NAMES:
26732670
pep_613 = True
26742671
if not pep_613 and s.unanalyzed_type is not None:
26752672
# Second rule: Explicit type (cls: Type[A] = A) always creates variable, not alias.
@@ -3410,7 +3407,7 @@ def is_final_type(self, typ: Optional[Type]) -> bool:
34103407
sym = self.lookup_qualified(typ.name, typ)
34113408
if not sym or not sym.node:
34123409
return False
3413-
return sym.node.fullname in ('typing.Final', 'typing_extensions.Final')
3410+
return sym.node.fullname in FINAL_TYPE_NAMES
34143411

34153412
def fail_invalid_classvar(self, context: Context) -> None:
34163413
self.fail(message_registry.CLASS_VAR_OUTSIDE_OF_CLASS, context)

mypy/typeanal.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
StarType, PartialType, EllipsisType, UninhabitedType, TypeType, CallableArgument,
1818
TypeQuery, union_items, TypeOfAny, LiteralType, RawExpressionType,
1919
PlaceholderType, Overloaded, get_proper_type, TypeAliasType, RequiredType,
20-
TypeVarLikeType, ParamSpecType, ParamSpecFlavor, callable_with_ellipsis
20+
TypeVarLikeType, ParamSpecType, ParamSpecFlavor, callable_with_ellipsis,
21+
TYPE_ALIAS_NAMES, FINAL_TYPE_NAMES, LITERAL_TYPE_NAMES, ANNOTATED_TYPE_NAMES,
2122
)
2223

2324
from mypy.nodes import (
@@ -42,10 +43,8 @@
4243
'typing.Tuple',
4344
'typing.Type',
4445
'typing.Union',
45-
'typing.Literal',
46-
'typing_extensions.Literal',
47-
'typing.Annotated',
48-
'typing_extensions.Annotated',
46+
*LITERAL_TYPE_NAMES,
47+
*ANNOTATED_TYPE_NAMES,
4948
}
5049

5150
ARG_KINDS_BY_CONSTRUCTOR: Final = {
@@ -262,7 +261,7 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool)
262261
return res
263262
elif isinstance(node, TypeInfo):
264263
return self.analyze_type_with_type_info(node, t.args, t)
265-
elif node.fullname in ("typing_extensions.TypeAlias", "typing.TypeAlias"):
264+
elif node.fullname in TYPE_ALIAS_NAMES:
266265
return AnyType(TypeOfAny.special_form)
267266
else:
268267
return self.analyze_unbound_type_without_type_info(t, sym, defining_literal)
@@ -286,7 +285,7 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Opt
286285
return NoneType()
287286
elif fullname == 'typing.Any' or fullname == 'builtins.Any':
288287
return AnyType(TypeOfAny.explicit)
289-
elif fullname in ('typing.Final', 'typing_extensions.Final'):
288+
elif fullname in FINAL_TYPE_NAMES:
290289
self.fail("Final can be only used as an outermost qualifier"
291290
" in a variable annotation", t)
292291
return AnyType(TypeOfAny.from_error)
@@ -351,9 +350,9 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Opt
351350
return self.anal_type(t.args[0])
352351
elif fullname in ('mypy_extensions.NoReturn', 'typing.NoReturn'):
353352
return UninhabitedType(is_noreturn=True)
354-
elif fullname in ('typing_extensions.Literal', 'typing.Literal'):
353+
elif fullname in LITERAL_TYPE_NAMES:
355354
return self.analyze_literal_type(t)
356-
elif fullname in ('typing_extensions.Annotated', 'typing.Annotated'):
355+
elif fullname in ANNOTATED_TYPE_NAMES:
357356
if len(t.args) < 2:
358357
self.fail("Annotated[...] must have exactly one type argument"
359358
" and at least one annotation", t)
@@ -1287,11 +1286,9 @@ def visit_unbound_type(self, t: UnboundType) -> TypeVarLikeList:
12871286
return [(name, node.node)]
12881287
elif not self.include_callables and self._seems_like_callable(t):
12891288
return []
1290-
elif node and node.fullname in ('typing_extensions.Literal', 'typing.Literal'):
1289+
elif node and node.fullname in LITERAL_TYPE_NAMES:
12911290
return []
1292-
elif (node
1293-
and node.fullname in ('typing_extensions.Annotated', 'typing.Annotated')
1294-
and t.args):
1291+
elif node and node.fullname in ANNOTATED_TYPE_NAMES and t.args:
12951292
# Don't query the second argument to Annotated for TypeVars
12961293
return self.query_types([t.args[0]])
12971294
else:

mypy/types.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,42 @@
8181
"mypy_extensions._TypedDict",
8282
)
8383

84+
# Supported names of Protocol base class.
85+
PROTOCOL_NAMES: Final = (
86+
'typing.Protocol',
87+
'typing_extensions.Protocol',
88+
)
89+
90+
# Supported TypeAlias names.
91+
TYPE_ALIAS_NAMES: Final = (
92+
"typing.TypeAlias",
93+
"typing_extensions.TypeAlias",
94+
)
95+
96+
# Supported Final type names.
97+
FINAL_TYPE_NAMES: Final = (
98+
'typing.Final',
99+
'typing_extensions.Final',
100+
)
101+
102+
# Supported @final decorator names.
103+
FINAL_DECORATOR_NAMES: Final = (
104+
'typing.final',
105+
'typing_extensions.final',
106+
)
107+
108+
# Supported Literal type names.
109+
LITERAL_TYPE_NAMES: Final = (
110+
'typing.Literal',
111+
'typing_extensions.Literal',
112+
)
113+
114+
# Supported Annotated type names.
115+
ANNOTATED_TYPE_NAMES: Final = (
116+
'typing.Annotated',
117+
'typing_extensions.Annotated',
118+
)
119+
84120
# A placeholder used for Bogus[...] parameters
85121
_dummy: Final[Any] = object()
86122

0 commit comments

Comments
 (0)
0