Skip to content

Commit

Permalink
Fix used-before-assignment for conditional self-referential typing (
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielNoord committed Dec 18, 2021
1 parent 57916d5 commit bb9cb4b
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ Release date: TBA

Closes #3793

* Fixed false positive for ``used-before-assignment`` with self-referential type
annotation in conditional statements within class methods.

Closes #5499

* ``used-before-assignment`` now assumes that assignments in except blocks
may not have occurred and warns accordingly.

Expand Down
5 changes: 5 additions & 0 deletions doc/whatsnew/2.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ Other Changes

Closes #3793

* Fixed false positive for ``used-before-assignment`` with self-referential type
annotation in conditional statements within class methods.

Closes #5499

* ``used-before-assignment`` now assumes that assignments in except blocks
may not have occurred and warns accordingly.

Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1817,7 +1817,7 @@ def _is_first_level_self_reference(
"""
if (
node.frame().parent == defstmt
and node.statement(future=True) not in node.frame().body
and node.statement(future=True) == node.frame()
):
# Check if used as type annotation
# Break but don't emit message if postponed evaluation is enabled
Expand Down
13 changes: 13 additions & 0 deletions tests/functional/u/use/used_before_assignment_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,16 @@ def inner_method(self, other: MyOtherClass) -> bool:
def self_referential_optional_within_method(self) -> None:
variable: Optional[MyOtherClass] = self
print(variable)


class MyThirdClass:
"""Class to test self referential variable typing within conditionals.
This regressed, reported in: https://github.com/PyCQA/pylint/issues/5499
"""

def function(self, var: int) -> None:
if var < 0.5:
_x: MyThirdClass = self

def other_function(self) -> None:
_x: MyThirdClass = self

0 comments on commit bb9cb4b

Please sign in to comment.