Skip to content

Commit 6d0b37d

Browse files
Fix pylint-dev#4045: Don't assume try ancestors are immediate parents when emitting used-before-assignment
1 parent 11381fa commit 6d0b37d

File tree

5 files changed

+20
-2
lines changed

5 files changed

+20
-2
lines changed

ChangeLog

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ Release date: TBA
1616

1717
Closes #85, #2615
1818

19+
* Fixed false negative for ``used-before-assignment`` when a conditional
20+
or context manager intervened before the try statement that suggested
21+
it might fail.
22+
23+
Closes #4045
24+
1925
* Fixed extremely long processing of long lines with comma's.
2026

2127
Closes #5483

doc/whatsnew/2.13.rst

+6
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ Other Changes
6363

6464
Closes #85, #2615
6565

66+
* Fixed false negative for ``used-before-assignment`` when a conditional
67+
or context manager intervened before the try statement that suggested
68+
it might fail.
69+
70+
Closes #4045
71+
6672
* Fix a false positive for ``assigning-non-slot`` when the slotted class
6773
defined ``__setattr__``.
6874

pylint/checkers/variables.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,9 @@ def _uncertain_nodes_in_try_blocks_when_evaluating_except_blocks(
747747
)
748748
if other_node_try_ancestor is None:
749749
continue
750-
if other_node_statement not in other_node_try_ancestor.body:
750+
if isinstance(other_node_statement, nodes.ExceptHandler):
751+
continue
752+
if isinstance(other_node_statement.parent, nodes.ExceptHandler):
751753
continue
752754
if node_statement.parent not in other_node_try_ancestor.handlers:
753755
continue

tests/functional/u/use/used_before_assignment_issue2615.py

+4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ def main():
44
try:
55
res = 1 / 0
66
res = 42
7+
if main():
8+
res = None
9+
with open(__file__, encoding="utf-8") as opened_file:
10+
res = opened_file.readlines()
711
except ZeroDivisionError:
812
print(res) # [used-before-assignment]
913
print(res)
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
used-before-assignment:8:14:8:17:main:Using variable 'res' before assignment:UNDEFINED
1+
used-before-assignment:12:14:12:17:main:Using variable 'res' before assignment:UNDEFINED

0 commit comments

Comments
 (0)