MCPcopy Create free account
hub / github.com/python/mypy / check_valid_comprehension

Method check_valid_comprehension

mypy/semanal.py:3267–3287  ·  view source on GitHub ↗

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.

(self, s: AssignmentExpr)

Source from the content-addressed store, hash-verified

3265 self.analyze_lvalue(s.target, escape_comprehensions=True, has_explicit_value=True)
3266
3267 def check_valid_comprehension(self, s: AssignmentExpr) -> bool:
3268 """Check that assignment expression is not nested within comprehension at class scope.
3269
3270 class C:
3271 [(j := i) for i in [1, 2, 3]]
3272 is a syntax error that is not enforced by Python parser, but at later steps.
3273 """
3274 for i, scope_type in enumerate(reversed(self.scope_stack)):
3275 if scope_type != SCOPE_COMPREHENSION and i < len(self.locals) - 1:
3276 if self.locals[-1 - i] is None:
3277 self.fail(
3278 "Assignment expression within a comprehension"
3279 " cannot be used in a class body",
3280 s,
3281 code=codes.SYNTAX,
3282 serious=True,
3283 blocker=True,
3284 )
3285 return False
3286 break
3287 return True
3288
3289 def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
3290 self.statement = s

Callers 1

visit_assignment_exprMethod · 0.95

Calls 4

failMethod · 0.95
enumerateFunction · 0.85
reversedFunction · 0.85
lenFunction · 0.85

Tested by

no test coverage detected