diff options
author | Jacob Walls <jwalls@azavea.com> | 2022-08-20 17:05:07 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-08-20 17:05:07 -0400 |
commit | 2fafadc8aca1831c594cafd35a46b691eaa3e357 (patch) | |
tree | 3616a3aba8f8baafe05c868d0d0fcc2543d74827 | |
parent | 2e2f20890097c59f2d4408b8adf27f1203c67412 (diff) | |
download | pylint-git-2fafadc8aca1831c594cafd35a46b691eaa3e357.tar.gz |
Fix `undefined-loop-variable` from walrus in comprehension test (#7324)
-rw-r--r-- | doc/whatsnew/fragments/7222.bugfix | 3 | ||||
-rw-r--r-- | pylint/checkers/variables.py | 18 | ||||
-rw-r--r-- | tests/functional/u/undefined/undefined_loop_variable_py38.py | 8 | ||||
-rw-r--r-- | tests/functional/u/undefined/undefined_loop_variable_py38.rc | 2 |
4 files changed, 31 insertions, 0 deletions
diff --git a/doc/whatsnew/fragments/7222.bugfix b/doc/whatsnew/fragments/7222.bugfix new file mode 100644 index 000000000..0d18e73da --- /dev/null +++ b/doc/whatsnew/fragments/7222.bugfix @@ -0,0 +1,3 @@ +Fix `undefined-loop-variable` from walrus in comprehension test. + +Closes #7222 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index e6af22689..3249a4b36 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -2249,6 +2249,24 @@ class VariablesChecker(BaseChecker): ): return + maybe_walrus = utils.get_node_first_ancestor_of_type(node, nodes.NamedExpr) + if maybe_walrus: + maybe_comprehension = utils.get_node_first_ancestor_of_type( + maybe_walrus, nodes.Comprehension + ) + if maybe_comprehension: + comprehension_scope = utils.get_node_first_ancestor_of_type( + maybe_comprehension, nodes.ComprehensionScope + ) + if comprehension_scope is None: + # Should not be possible. + pass + elif ( + comprehension_scope.parent.scope() is scope + and node.name in comprehension_scope.locals + ): + return + # For functions we can do more by inferring the length of the itered object try: inferred = next(assign.iter.infer()) diff --git a/tests/functional/u/undefined/undefined_loop_variable_py38.py b/tests/functional/u/undefined/undefined_loop_variable_py38.py new file mode 100644 index 000000000..5778df7d2 --- /dev/null +++ b/tests/functional/u/undefined/undefined_loop_variable_py38.py @@ -0,0 +1,8 @@ +"""Tests for undefined-loop-variable with assignment expressions""" + + +def walrus_in_comprehension_test(container): + """https://github.com/PyCQA/pylint/issues/7222""" + for something in container: + print(something) + print([my_test for something in container if (my_test := something)]) diff --git a/tests/functional/u/undefined/undefined_loop_variable_py38.rc b/tests/functional/u/undefined/undefined_loop_variable_py38.rc new file mode 100644 index 000000000..85fc502b3 --- /dev/null +++ b/tests/functional/u/undefined/undefined_loop_variable_py38.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 |