Skip to content

Commit b6aad35

Browse files
Fix pylint-dev#5500: Fix false-positive used-before-assignment for assignments in except blocks following try blocks that return
1 parent bd55b27 commit b6aad35

File tree

4 files changed

+27
-0
lines changed

4 files changed

+27
-0
lines changed

ChangeLog

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ Release date: TBA
1616

1717
Closes #4761
1818

19+
* When evaluating statements after an except block, ``used-before-assignment``
20+
assumes that assignments in the except blocks took place if the
21+
corresponding try block contained a return statement.
22+
23+
Closes #5500
24+
1925
* ``used-before-assignment`` now checks names in try blocks.
2026

2127
* Some files in ``pylint.testutils`` were deprecated. In the future imports should be done from the

doc/whatsnew/2.13.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ Other Changes
3636

3737
Closes #4761
3838

39+
* When evaluating statements after an except block, ``used-before-assignment``
40+
assumes that assignments in the except blocks took place if the
41+
corresponding try block contained a return statement.
42+
43+
Closes #5500
44+
3945
* ``used-before-assignment`` now checks names in try blocks.
4046

4147
* Require Python ``3.6.2`` to run pylint.

pylint/checkers/variables.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,12 @@ def get_next_to_consume(self, node):
654654
and isinstance(
655655
n.statement(future=True).parent.parent, nodes.TryExcept
656656
)
657+
# If the try block returns we assume that assignments in the except
658+
# handlers could have happened.
659+
and not any(
660+
isinstance(try_statement, nodes.Return)
661+
for try_statement in n.statement(future=True).parent.parent.body
662+
)
657663
)
658664
or n.statement(future=True).parent.parent_of(node)
659665
]
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
"""used-before-assignment (E0601)"""
2+
def function():
3+
"""Assume except blocks execute if the try block returns."""
4+
try:
5+
return "success message"
6+
except ValueError:
7+
failure_message = "failure message"
8+
9+
return failure_message

0 commit comments

Comments
 (0)