63
63
YieldFromExpr , NamedTupleExpr , NonlocalDecl ,
64
64
SetComprehension , DictionaryComprehension , TYPE_ALIAS , TypeAliasExpr ,
65
65
YieldExpr , ExecStmt , Argument , BackquoteExpr , ImportBase , COVARIANT , CONTRAVARIANT ,
66
+ IntExpr , FloatExpr , UnicodeExpr ,
66
67
INVARIANT , UNBOUND_IMPORTED
67
68
)
68
69
from mypy .visitor import NodeVisitor
@@ -1043,8 +1044,11 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
1043
1044
s .type = self .anal_type (s .type , allow_tuple_literal )
1044
1045
else :
1045
1046
# For simple assignments, allow binding type aliases.
1047
+ # Also set the type if the rvalue is a simple literal.
1046
1048
if (s .type is None and len (s .lvalues ) == 1 and
1047
1049
isinstance (s .lvalues [0 ], NameExpr )):
1050
+ if s .lvalues [0 ].is_def :
1051
+ s .type = self .analyze_simple_literal_type (s .rvalue )
1048
1052
res = analyze_type_alias (s .rvalue ,
1049
1053
self .lookup_qualified ,
1050
1054
self .lookup_fully_qualified ,
@@ -1070,6 +1074,20 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
1070
1074
isinstance (s .rvalue , (ListExpr , TupleExpr ))):
1071
1075
self .add_exports (* s .rvalue .items )
1072
1076
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
+
1073
1091
def check_and_set_up_type_alias (self , s : AssignmentStmt ) -> None :
1074
1092
"""Check if assignment creates a type alias and set it up as needed."""
1075
1093
# For now, type aliases only work at the top level of a module.
0 commit comments