From bb9cb4b4428d2e5769737e9ca23e46e85614412a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Sat, 18 Dec 2021 11:10:20 +0100 Subject: Fix ``used-before-assignment`` for conditional self-referential typing (#5532) --- ChangeLog | 5 +++++ doc/whatsnew/2.13.rst | 5 +++++ pylint/checkers/variables.py | 2 +- tests/functional/u/use/used_before_assignment_typing.py | 13 +++++++++++++ 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 5ea915f92..08b017a63 100644 --- a/ChangeLog +++ b/ChangeLog @@ -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. diff --git a/doc/whatsnew/2.13.rst b/doc/whatsnew/2.13.rst index 4264bb61c..c5e33bb64 100644 --- a/doc/whatsnew/2.13.rst +++ b/doc/whatsnew/2.13.rst @@ -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. diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 315698c58..40fc99b63 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -1817,7 +1817,7 @@ class VariablesChecker(BaseChecker): """ 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 diff --git a/tests/functional/u/use/used_before_assignment_typing.py b/tests/functional/u/use/used_before_assignment_typing.py index a9961c890..33d81356e 100644 --- a/tests/functional/u/use/used_before_assignment_typing.py +++ b/tests/functional/u/use/used_before_assignment_typing.py @@ -61,3 +61,16 @@ class MyOtherClass: 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 -- cgit v1.2.1