Skip to content

Commit 67055f4

Browse files
Fix used-before-assignment false positive for except handler names shared by comprehension test (#5818)
1 parent 8c0062f commit 67055f4

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

ChangeLog

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,11 @@ Release date: TBA
287287

288288
Closes #4716
289289

290+
* Fix false positive for ``used-before-assignment`` when an except handler
291+
shares a name with a test in a filtered comprehension.
292+
293+
Closes #5817
294+
290295
* Fix crash in ``unnecessary-dict-index-lookup`` checker if the output of
291296
``items()`` is assigned to a 1-tuple.
292297

doc/whatsnew/2.13.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,11 @@ Other Changes
184184

185185
Closes #4716
186186

187+
* Fix false positive for ``used-before-assignment`` when an except handler
188+
shares a name with a test in a filtered comprehension.
189+
190+
Closes #5817
191+
187192
* Fix a crash in ``unused-private-member`` checker when analyzing code using
188193
``type(self)`` in bound methods.
189194

pylint/checkers/variables.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,12 @@ def get_next_to_consume(self, node: nodes.Name) -> Optional[List[nodes.NodeNG]]:
646646
found_nodes = None
647647

648648
# Filter out assignments in ExceptHandlers that node is not contained in
649-
if found_nodes:
649+
# unless this is a test in a filtered comprehension
650+
# Example: [e for e in range(3) if e] <--- followed by except e:
651+
if found_nodes and (
652+
not isinstance(parent_node, nodes.Comprehension)
653+
or node not in parent_node.ifs
654+
):
650655
found_nodes = [
651656
n
652657
for n in found_nodes

tests/functional/u/used/used_before_assignment_issue626.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,10 @@ def main4():
4242
pass
4343

4444
print(e) # [used-before-assignment]
45+
46+
47+
def main5():
48+
try:
49+
print([e for e in range(3) if e])
50+
except ValueError as e:
51+
print(e)

0 commit comments

Comments
 (0)