diff --git a/ChangeLog b/ChangeLog index e27ef4cb27..b42d81a8f9 100644 --- a/ChangeLog +++ b/ChangeLog @@ -287,6 +287,11 @@ Release date: TBA Closes #4716 +* Fix false positive for ``used-before-assignment`` when an except handler + shares a name with a test in a filtered comprehension. + + Closes #5817 + * Fix crash in ``unnecessary-dict-index-lookup`` checker if the output of ``items()`` is assigned to a 1-tuple. diff --git a/doc/whatsnew/2.13.rst b/doc/whatsnew/2.13.rst index 57afc70fa2..fa5b162ce8 100644 --- a/doc/whatsnew/2.13.rst +++ b/doc/whatsnew/2.13.rst @@ -184,6 +184,11 @@ Other Changes Closes #4716 +* Fix false positive for ``used-before-assignment`` when an except handler + shares a name with a test in a filtered comprehension. + + Closes #5817 + * Fix a crash in ``unused-private-member`` checker when analyzing code using ``type(self)`` in bound methods. diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 90eee481f0..836d1947e3 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -646,7 +646,12 @@ def get_next_to_consume(self, node: nodes.Name) -> Optional[List[nodes.NodeNG]]: found_nodes = None # Filter out assignments in ExceptHandlers that node is not contained in - if found_nodes: + # unless this is a test in a filtered comprehension + # Example: [e for e in range(3) if e] <--- followed by except e: + if found_nodes and ( + not isinstance(parent_node, nodes.Comprehension) + or node not in parent_node.ifs + ): found_nodes = [ n for n in found_nodes diff --git a/tests/functional/u/used/used_before_assignment_issue626.py b/tests/functional/u/used/used_before_assignment_issue626.py index c98632b7f7..cb9fc100e6 100644 --- a/tests/functional/u/used/used_before_assignment_issue626.py +++ b/tests/functional/u/used/used_before_assignment_issue626.py @@ -42,3 +42,10 @@ def main4(): pass print(e) # [used-before-assignment] + + +def main5(): + try: + print([e for e in range(3) if e]) + except ValueError as e: + print(e)