diff --git a/ChangeLog b/ChangeLog index 93292a4112..6d4239fa12 100644 --- a/ChangeLog +++ b/ChangeLog @@ -96,6 +96,12 @@ Release date: TBA Closes #5360, #3877 +* Fixed a false positive (affecting unreleased development) for + ``used-before-assignment`` involving homonyms between filtered comprehensions + and assignments in except blocks. + + Closes #5586 + * Fixed crash with slots assignments and annotated assignments. Closes #5479 diff --git a/doc/whatsnew/2.13.rst b/doc/whatsnew/2.13.rst index 10e8c5b689..74499108d3 100644 --- a/doc/whatsnew/2.13.rst +++ b/doc/whatsnew/2.13.rst @@ -139,6 +139,12 @@ Other Changes Closes #5360, #3877 +* Fixed a false positive (affecting unreleased development) for + ``used-before-assignment`` involving homonyms between filtered comprehensions + and assignments in except blocks. + + Closes #5586 + * Fixed crash on list comprehensions that used ``type`` as inner variable name. Closes #5461 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 66af3ec940..bc291c1b9e 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -1316,6 +1316,13 @@ def _check_consumer( if utils.is_func_decorator(current_consumer.node) or not ( current_consumer.scope_type == "comprehension" and self._has_homonym_in_upper_function_scope(node, consumer_level) + # But don't catch homonyms against the filter of a comprehension, + # (like "if x" in "[x for x in expr() if x]") + # https://github.com/PyCQA/pylint/issues/5586 + and not ( + isinstance(node.parent.parent, nodes.Comprehension) + and node.parent in node.parent.parent.ifs + ) ): self._check_late_binding_closure(node) self._loopvar_name(node) diff --git a/tests/functional/u/use/used_before_assignment_filtered_comprehension.py b/tests/functional/u/use/used_before_assignment_filtered_comprehension.py new file mode 100644 index 0000000000..f638b0be9b --- /dev/null +++ b/tests/functional/u/use/used_before_assignment_filtered_comprehension.py @@ -0,0 +1,9 @@ +"""Homonym between filtered comprehension and assignment in except block.""" + +def func(): + """https://github.com/PyCQA/pylint/issues/5586""" + try: + print(value for value in range(1 / 0) if isinstance(value, int)) + except ZeroDivisionError: + value = 1 + print(value)