@@ -405,7 +405,8 @@ def _has_locals_call_after_node(stmt, scope):
405
405
"E0601" : (
406
406
"Using variable %r before assignment" ,
407
407
"used-before-assignment" ,
408
- "Used when a local variable is accessed before its assignment." ,
408
+ "Used when a local variable is accessed before its assignment or in "
409
+ "except or finally blocks without being defined before the try block." ,
409
410
),
410
411
"E0602" : (
411
412
"Undefined variable %r" ,
@@ -662,6 +663,49 @@ def get_next_to_consume(self, node):
662
663
self .consumed_uncertain [node .name ] += difference
663
664
found_nodes = filtered_nodes
664
665
666
+ # If this node is in a Finally block of a Try/Finally,
667
+ # filter out assignments in the try portion, assuming they may fail
668
+ if (
669
+ found_nodes
670
+ and isinstance (node .statement (future = True ).parent , nodes .TryFinally )
671
+ and node .statement (future = True )
672
+ in node .statement (future = True ).parent .finalbody
673
+ ):
674
+ filtered_nodes = [
675
+ n
676
+ for n in found_nodes
677
+ if not (
678
+ n .statement (future = True ).parent
679
+ is node .statement (future = True ).parent
680
+ and n .statement (future = True ) in n .statement (future = True ).parent .body
681
+ )
682
+ ]
683
+ filtered_nodes_set = set (filtered_nodes )
684
+ difference = [n for n in found_nodes if n not in filtered_nodes_set ]
685
+ self .consumed_uncertain [node .name ] += difference
686
+ found_nodes = filtered_nodes
687
+
688
+ # If this node is in an ExceptHandler,
689
+ # filter out assignments in the try portion, assuming they may fail
690
+ if found_nodes and isinstance (
691
+ node .statement (future = True ).parent , nodes .ExceptHandler
692
+ ):
693
+ filtered_nodes = [
694
+ n
695
+ for n in found_nodes
696
+ if not (
697
+ isinstance (n .statement (future = True ).parent , nodes .TryExcept )
698
+ and n .statement (future = True ) in n .statement (future = True ).parent .body
699
+ and node .statement (future = True ).parent
700
+ in n .statement (future = True ).parent .handlers
701
+ and n .statement (future = True ) in n .statement (future = True ).parent .body
702
+ )
703
+ ]
704
+ filtered_nodes_set = set (filtered_nodes )
705
+ difference = [n for n in found_nodes if n not in filtered_nodes_set ]
706
+ self .consumed_uncertain [node .name ] += difference
707
+ found_nodes = filtered_nodes
708
+
665
709
return found_nodes
666
710
667
711
0 commit comments