Skip to content

Commit 1fe8332

Browse files
Add exception for finally statements executing before the return
1 parent 6cf3109 commit 1fe8332

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

pylint/checkers/variables.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -659,9 +659,22 @@ def get_next_to_consume(self, node):
659659
)
660660
# If the try block returns we assume that assignments in the except
661661
# handlers could have happened.
662-
and not any(
663-
isinstance(try_statement, nodes.Return)
664-
for try_statement in n.statement(future=True).parent.parent.body
662+
and (
663+
not any(
664+
isinstance(try_statement, nodes.Return)
665+
for try_statement in n.statement(
666+
future=True
667+
).parent.parent.body
668+
)
669+
# But not if this node is in the final block, which will
670+
# execute before the return.
671+
or (
672+
isinstance(node_statement.parent, nodes.TryFinally)
673+
and node_statement in node_statement.parent.finalbody
674+
and n.statement(future=True).parent.parent.parent.parent_of(
675+
node_statement
676+
)
677+
)
665678
)
666679
)
667680
or n.statement(future=True).parent.parent_of(node)
Lines changed: 15 additions & 0 deletions
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
Lines changed: 1 addition & 0 deletions
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)