Skip to content

Commit ff1199b

Browse files
authored
Fix simple literal inference in class bodies in import cycle (#13552)
This fixes a little regression caused by #13494
1 parent b29051c commit ff1199b

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

mypy/semanal.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -3007,11 +3007,14 @@ def process_type_annotation(self, s: AssignmentStmt) -> None:
30073007
):
30083008
self.fail("All protocol members must have explicitly declared types", s)
30093009
# Set the type if the rvalue is a simple literal (even if the above error occurred).
3010-
# We skip this step for type scope because it messes up with class attribute
3011-
# inference for literal types (also annotated and non-annotated variables at class
3012-
# scope are semantically different, so we should not souch statement type).
3013-
if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr) and not self.type:
3014-
if s.lvalues[0].is_inferred_def:
3010+
if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr):
3011+
ref_expr = s.lvalues[0]
3012+
safe_literal_inference = True
3013+
if self.type and isinstance(ref_expr, NameExpr) and len(self.type.mro) > 1:
3014+
# Check if there is a definition in supertype. If yes, we can't safely
3015+
# decide here what to infer: int or Literal[42].
3016+
safe_literal_inference = self.type.mro[1].get(ref_expr.name) is None
3017+
if safe_literal_inference and ref_expr.is_inferred_def:
30153018
s.type = self.analyze_simple_literal_type(s.rvalue, s.is_final_def)
30163019
if s.type:
30173020
# Store type into nodes.

test-data/unit/check-inference.test

+16
Original file line numberDiff line numberDiff line change
@@ -3337,3 +3337,19 @@ class A:
33373337
class B(A):
33383338
args = value
33393339
[builtins fixtures/dict.pyi]
3340+
3341+
[case testInferSimpleLiteralInClassBodyCycle]
3342+
import a
3343+
[file a.py]
3344+
import b
3345+
reveal_type(b.B.x)
3346+
class A:
3347+
x = 42
3348+
[file b.py]
3349+
import a
3350+
reveal_type(a.A.x)
3351+
class B:
3352+
x = 42
3353+
[out]
3354+
tmp/b.py:2: note: Revealed type is "builtins.int"
3355+
tmp/a.py:2: note: Revealed type is "builtins.int"

0 commit comments

Comments
 (0)