Skip to content

Commit 12af55b

Browse files
author
Guido van Rossum
committed
Set the type of x = 0 and similar in the semantic analyzer.
This thwarts certain kinds of errors due to circular dependencies (see #1530).
1 parent ad9024d commit 12af55b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

mypy/semanal.py

+18
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
YieldFromExpr, NamedTupleExpr, NonlocalDecl,
6464
SetComprehension, DictionaryComprehension, TYPE_ALIAS, TypeAliasExpr,
6565
YieldExpr, ExecStmt, Argument, BackquoteExpr, ImportBase, COVARIANT, CONTRAVARIANT,
66+
IntExpr, FloatExpr, UnicodeExpr,
6667
INVARIANT, UNBOUND_IMPORTED
6768
)
6869
from mypy.visitor import NodeVisitor
@@ -1043,8 +1044,11 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
10431044
s.type = self.anal_type(s.type, allow_tuple_literal)
10441045
else:
10451046
# For simple assignments, allow binding type aliases.
1047+
# Also set the type if the rvalue is a simple literal.
10461048
if (s.type is None and len(s.lvalues) == 1 and
10471049
isinstance(s.lvalues[0], NameExpr)):
1050+
if s.lvalues[0].is_def:
1051+
s.type = self.analyze_simple_literal_type(s.rvalue)
10481052
res = analyze_type_alias(s.rvalue,
10491053
self.lookup_qualified,
10501054
self.lookup_fully_qualified,
@@ -1070,6 +1074,20 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
10701074
isinstance(s.rvalue, (ListExpr, TupleExpr))):
10711075
self.add_exports(*s.rvalue.items)
10721076

1077+
def analyze_simple_literal_type(self, rvalue: Node) -> Optional[Type]:
1078+
"""Return builtins.int if rvalue is an int literal, etc."""
1079+
if isinstance(rvalue, IntExpr):
1080+
return self.named_type_or_none('builtins.int')
1081+
if isinstance(rvalue, FloatExpr):
1082+
return self.named_type_or_none('builtins.float')
1083+
if isinstance(rvalue, StrExpr):
1084+
return self.named_type_or_none('builtins.str')
1085+
if isinstance(rvalue, BytesExpr):
1086+
return self.named_type_or_none('builtins.bytes')
1087+
if isinstance(rvalue, UnicodeExpr):
1088+
return self.named_type_or_none('builtins.unicode')
1089+
return None
1090+
10731091
def check_and_set_up_type_alias(self, s: AssignmentStmt) -> None:
10741092
"""Check if assignment creates a type alias and set it up as needed."""
10751093
# For now, type aliases only work at the top level of a module.

0 commit comments

Comments
 (0)