Skip to content

Commit bb9cb4b

Browse files
authored
Fix used-before-assignment for conditional self-referential typing (#5532)
1 parent 57916d5 commit bb9cb4b

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed

ChangeLog

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ Release date: TBA
2525

2626
Closes #3793
2727

28+
* Fixed false positive for ``used-before-assignment`` with self-referential type
29+
annotation in conditional statements within class methods.
30+
31+
Closes #5499
32+
2833
* ``used-before-assignment`` now assumes that assignments in except blocks
2934
may not have occurred and warns accordingly.
3035

doc/whatsnew/2.13.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ Other Changes
6060

6161
Closes #3793
6262

63+
* Fixed false positive for ``used-before-assignment`` with self-referential type
64+
annotation in conditional statements within class methods.
65+
66+
Closes #5499
67+
6368
* ``used-before-assignment`` now assumes that assignments in except blocks
6469
may not have occurred and warns accordingly.
6570

pylint/checkers/variables.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1817,7 +1817,7 @@ def _is_first_level_self_reference(
18171817
"""
18181818
if (
18191819
node.frame().parent == defstmt
1820-
and node.statement(future=True) not in node.frame().body
1820+
and node.statement(future=True) == node.frame()
18211821
):
18221822
# Check if used as type annotation
18231823
# Break but don't emit message if postponed evaluation is enabled

tests/functional/u/use/used_before_assignment_typing.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,16 @@ def inner_method(self, other: MyOtherClass) -> bool:
6161
def self_referential_optional_within_method(self) -> None:
6262
variable: Optional[MyOtherClass] = self
6363
print(variable)
64+
65+
66+
class MyThirdClass:
67+
"""Class to test self referential variable typing within conditionals.
68+
This regressed, reported in: https://github.com/PyCQA/pylint/issues/5499
69+
"""
70+
71+
def function(self, var: int) -> None:
72+
if var < 0.5:
73+
_x: MyThirdClass = self
74+
75+
def other_function(self) -> None:
76+
_x: MyThirdClass = self

0 commit comments

Comments
 (0)