Skip to content

Commit

Permalink
allow assignment expressions to redefine outer names (#801)
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile authored Feb 17, 2024
1 parent 5d192ce commit b1f8362
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
19 changes: 11 additions & 8 deletions pyflakes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1003,14 +1003,17 @@ def addBinding(self, node, value):
# don't treat annotations as assignments if there is an existing value
# in scope
if value.name not in self.scope or not isinstance(value, Annotation):
cur_scope_pos = -1
# As per PEP 572, use scope in which outermost generator is defined
while (
isinstance(value, NamedExprAssignment) and
isinstance(self.scopeStack[cur_scope_pos], GeneratorScope)
):
cur_scope_pos -= 1
self.scopeStack[cur_scope_pos][value.name] = value
if isinstance(value, NamedExprAssignment):
# PEP 572: use scope in which outermost generator is defined
scope = next(
scope
for scope in reversed(self.scopeStack)
if not isinstance(scope, GeneratorScope)
)
# it may be a re-assignment to an already existing name
scope.setdefault(value.name, value)
else:
self.scope[value.name] = value

def _unknown_handler(self, node):
# this environment variable configures whether to error on unknown
Expand Down
7 changes: 7 additions & 0 deletions pyflakes/test/test_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -1717,6 +1717,13 @@ def test_assign_expr_generator_scope(self):
print(y)
''')

def test_assign_expr_generator_scope_reassigns_parameter(self):
self.flakes('''
def foo(x):
fns = [lambda x: x + 1, lambda x: x + 2, lambda x: x + 3]
return [(x := fn(x)) for fn in fns]
''')

def test_assign_expr_nested(self):
"""Test assignment expressions in nested expressions."""
self.flakes('''
Expand Down

0 comments on commit b1f8362

Please sign in to comment.