Skip to content
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

Fix a crash on walrus in comprehension at class scope #14556

Merged
merged 1 commit into from
Jan 29, 2023
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
25 changes: 25 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2658,8 +2658,33 @@ def visit_import_all(self, i: ImportAll) -> None:

def visit_assignment_expr(self, s: AssignmentExpr) -> None:
s.value.accept(self)
if self.is_func_scope():
if not self.check_valid_comprehension(s):
return
self.analyze_lvalue(s.target, escape_comprehensions=True, has_explicit_value=True)

def check_valid_comprehension(self, s: AssignmentExpr) -> bool:
"""Check that assignment expression is not nested within comprehension at class scope.

class C:
[(j := i) for i in [1, 2, 3]]
is a syntax error that is not enforced by Python parser, but at later steps.
"""
for i, is_comprehension in enumerate(reversed(self.is_comprehension_stack)):
if not is_comprehension and i < len(self.locals) - 1:
if self.locals[-1 - i] is None:
self.fail(
"Assignment expression within a comprehension"
" cannot be used in a class body",
s,
code=codes.SYNTAX,
serious=True,
blocker=True,
)
return False
break
return True

def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
self.statement = s

Expand Down
5 changes: 5 additions & 0 deletions test-data/unit/check-python38.test
Original file line number Diff line number Diff line change
Expand Up @@ -734,3 +734,8 @@ class C(Generic[T]):
[out]
main:10: note: Revealed type is "builtins.int"
main:10: note: Revealed type is "builtins.str"

[case testNoCrashOnAssignmentExprClass]
class C:
[(j := i) for i in [1, 2, 3]] # E: Assignment expression within a comprehension cannot be used in a class body
[builtins fixtures/list.pyi]
4 changes: 4 additions & 0 deletions test-data/unit/check-statements.test
Original file line number Diff line number Diff line change
Expand Up @@ -2194,3 +2194,7 @@ class B: pass

def foo(x: int) -> Union[Generator[A, None, None], Generator[B, None, None]]:
yield x # E: Incompatible types in "yield" (actual type "int", expected type "Union[A, B]")

[case testNoCrashOnStarRightHandSide]
x = *(1, 2, 3) # E: Can use starred expression only as assignment target
[builtins fixtures/tuple.pyi]