@@ -629,13 +629,12 @@ def get_next_to_consume(self, node: nodes.Name) -> Optional[List[nodes.NodeNG]]:
629
629
):
630
630
return found_nodes
631
631
632
+ # And is not part of a test in a filtered comprehension
633
+ if VariablesChecker ._has_homonym_in_comprehension_test (node ):
634
+ return found_nodes
635
+
632
636
# Filter out assignments in ExceptHandlers that node is not contained in
633
- # unless this is a test in a filtered comprehension
634
- # Example: [e for e in range(3) if e] <--- followed by except e:
635
- if found_nodes and (
636
- not isinstance (parent_node , nodes .Comprehension )
637
- or node not in parent_node .ifs
638
- ):
637
+ if found_nodes :
639
638
found_nodes = [
640
639
n
641
640
for n in found_nodes
@@ -1506,10 +1505,7 @@ def _check_consumer(
1506
1505
# (like "if x" in "[x for x in expr() if x]")
1507
1506
# https://github.com/PyCQA/pylint/issues/5586
1508
1507
and not (
1509
- (
1510
- isinstance (node .parent .parent , nodes .Comprehension )
1511
- and node .parent in node .parent .parent .ifs
1512
- )
1508
+ self ._has_homonym_in_comprehension_test (node )
1513
1509
# Or homonyms against values to keyword arguments
1514
1510
# (like "var" in "[func(arg=var) for var in expr()]")
1515
1511
or (
@@ -2482,6 +2478,30 @@ def _has_homonym_in_upper_function_scope(
2482
2478
for _consumer in self ._to_consume [index - 1 :: - 1 ]
2483
2479
)
2484
2480
2481
+ @staticmethod
2482
+ def _has_homonym_in_comprehension_test (node : nodes .Name ) -> bool :
2483
+ """Return True if `node`'s frame contains a comprehension employing an
2484
+ identical name in a test.
2485
+
2486
+ The name in the test could appear at varying depths:
2487
+
2488
+ Examples:
2489
+ [x for x in range(3) if name]
2490
+ [x for x in range(3) if name.num == 1]
2491
+ [x for x in range(3)] if call(name.num)]
2492
+ """
2493
+ closest_comprehension = utils .get_node_first_ancestor_of_type (
2494
+ node , nodes .Comprehension
2495
+ )
2496
+ return (
2497
+ closest_comprehension is not None
2498
+ and node .frame (future = True ).parent_of (closest_comprehension )
2499
+ and any (
2500
+ test is node or test .parent_of (node )
2501
+ for test in closest_comprehension .ifs
2502
+ )
2503
+ )
2504
+
2485
2505
def _store_type_annotation_node (self , type_annotation ):
2486
2506
"""Given a type annotation, store all the name nodes it refers to."""
2487
2507
if isinstance (type_annotation , nodes .Name ):
0 commit comments