Skip to content

Commit b1f8362

Browse files
authored
allow assignment expressions to redefine outer names (#801)
1 parent 5d192ce commit b1f8362

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

pyflakes/checker.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -1003,14 +1003,17 @@ def addBinding(self, node, value):
10031003
# don't treat annotations as assignments if there is an existing value
10041004
# in scope
10051005
if value.name not in self.scope or not isinstance(value, Annotation):
1006-
cur_scope_pos = -1
1007-
# As per PEP 572, use scope in which outermost generator is defined
1008-
while (
1009-
isinstance(value, NamedExprAssignment) and
1010-
isinstance(self.scopeStack[cur_scope_pos], GeneratorScope)
1011-
):
1012-
cur_scope_pos -= 1
1013-
self.scopeStack[cur_scope_pos][value.name] = value
1006+
if isinstance(value, NamedExprAssignment):
1007+
# PEP 572: use scope in which outermost generator is defined
1008+
scope = next(
1009+
scope
1010+
for scope in reversed(self.scopeStack)
1011+
if not isinstance(scope, GeneratorScope)
1012+
)
1013+
# it may be a re-assignment to an already existing name
1014+
scope.setdefault(value.name, value)
1015+
else:
1016+
self.scope[value.name] = value
10141017

10151018
def _unknown_handler(self, node):
10161019
# this environment variable configures whether to error on unknown

pyflakes/test/test_other.py

+7
Original file line numberDiff line numberDiff line change
@@ -1717,6 +1717,13 @@ def test_assign_expr_generator_scope(self):
17171717
print(y)
17181718
''')
17191719

1720+
def test_assign_expr_generator_scope_reassigns_parameter(self):
1721+
self.flakes('''
1722+
def foo(x):
1723+
fns = [lambda x: x + 1, lambda x: x + 2, lambda x: x + 3]
1724+
return [(x := fn(x)) for fn in fns]
1725+
''')
1726+
17201727
def test_assign_expr_nested(self):
17211728
"""Test assignment expressions in nested expressions."""
17221729
self.flakes('''

0 commit comments

Comments
 (0)