Skip to content

Commit 3b28e7d

Browse files
Add exception for finally statements executing before the return
1 parent 1839085 commit 3b28e7d

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

pylint/checkers/variables.py

+17-3
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,7 @@ def get_next_to_consume(self, node):
621621
name = node.name
622622
parent_node = node.parent
623623
found_nodes = self.to_consume.get(name)
624+
node_statement = node.statement(future=True)
624625
if (
625626
found_nodes
626627
and isinstance(parent_node, nodes.Assign)
@@ -660,9 +661,22 @@ def get_next_to_consume(self, node):
660661
)
661662
# If the try block returns we assume that assignments in the except
662663
# handlers could have happened.
663-
and not any(
664-
isinstance(try_statement, nodes.Return)
665-
for try_statement in n.statement(future=True).parent.parent.body
664+
and (
665+
not any(
666+
isinstance(try_statement, nodes.Return)
667+
for try_statement in n.statement(
668+
future=True
669+
).parent.parent.body
670+
)
671+
# But not if this node is in the final block, which will
672+
# execute before the return.
673+
or (
674+
isinstance(node_statement.parent, nodes.TryFinally)
675+
and node_statement in node_statement.parent.finalbody
676+
and n.statement(future=True).parent.parent.parent.parent_of(
677+
node_statement
678+
)
679+
)
666680
)
667681
)
668682
or n.statement(future=True).parent.parent_of(node)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""Tests for used-before-assignment with assignments in except handlers after
2+
try blocks with return statements.
3+
See: https://github.com/PyCQA/pylint/issues/5500.
4+
"""
5+
def function():
6+
"""Assume except blocks execute if the try block returns."""
7+
try:
8+
success_message = "success message"
9+
return success_message
10+
except ValueError:
11+
failure_message = "failure message"
12+
finally:
13+
print(failure_message) # [used-before-assignment]
14+
15+
return failure_message
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
used-before-assignment:13:14:13:29:function:Using variable 'failure_message' before assignment:UNDEFINED

0 commit comments

Comments
 (0)