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

allow assignment expressions to redefine outer names #801

Merged
merged 1 commit into from
Feb 17, 2024
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
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 @@ -1707,6 +1707,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
Loading