Skip to content

Fix simple literal inference in class bodies in import cycle #13552

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3007,11 +3007,14 @@ def process_type_annotation(self, s: AssignmentStmt) -> None:
):
self.fail("All protocol members must have explicitly declared types", s)
# Set the type if the rvalue is a simple literal (even if the above error occurred).
# We skip this step for type scope because it messes up with class attribute
# inference for literal types (also annotated and non-annotated variables at class
# scope are semantically different, so we should not souch statement type).
if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr) and not self.type:
if s.lvalues[0].is_inferred_def:
if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr):
ref_expr = s.lvalues[0]
safe_literal_inference = True
if self.type and isinstance(ref_expr, NameExpr) and len(self.type.mro) > 1:
# Check if there is a definition in supertype. If yes, we can't safely
# decide here what to infer: int or Literal[42].
safe_literal_inference = self.type.mro[1].get(ref_expr.name) is None
if safe_literal_inference and ref_expr.is_inferred_def:
s.type = self.analyze_simple_literal_type(s.rvalue, s.is_final_def)
if s.type:
# Store type into nodes.
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -3337,3 +3337,19 @@ class A:
class B(A):
args = value
[builtins fixtures/dict.pyi]

[case testInferSimpleLiteralInClassBodyCycle]
import a
[file a.py]
import b
reveal_type(b.B.x)
class A:
x = 42
[file b.py]
import a
reveal_type(a.A.x)
class B:
x = 42
[out]
tmp/b.py:2: note: Revealed type is "builtins.int"
tmp/a.py:2: note: Revealed type is "builtins.int"