From 8aa08cb993d6249f7df7360aabf959705f90d58f Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Sat, 10 Feb 2024 15:19:39 -0500 Subject: [PATCH] allow assignment expressions to redefine outer names --- pyflakes/checker.py | 19 +++++++++++-------- pyflakes/test/test_other.py | 7 +++++++ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/pyflakes/checker.py b/pyflakes/checker.py index 754ab30c..a1c33272 100644 --- a/pyflakes/checker.py +++ b/pyflakes/checker.py @@ -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 diff --git a/pyflakes/test/test_other.py b/pyflakes/test/test_other.py index aebdceab..288e0a7f 100644 --- a/pyflakes/test/test_other.py +++ b/pyflakes/test/test_other.py @@ -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('''