From 5c22a794229d0bde15180f57b065c233765e208e Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Sat, 24 Sep 2022 08:49:01 -0400 Subject: Prevent `redefined-outer-name` for `if t.TYPE_CHECKING` --- doc/whatsnew/fragments/7524.bugfix | 4 ++++ pylint/checkers/variables.py | 4 +--- .../r/redefined/redefined_outer_name_type_checking.py | 12 ++++++++++-- 3 files changed, 15 insertions(+), 5 deletions(-) create mode 100644 doc/whatsnew/fragments/7524.bugfix diff --git a/doc/whatsnew/fragments/7524.bugfix b/doc/whatsnew/fragments/7524.bugfix new file mode 100644 index 000000000..8a9c5fc79 --- /dev/null +++ b/doc/whatsnew/fragments/7524.bugfix @@ -0,0 +1,4 @@ +Fix false positive for ``redefined-outer-name`` when aliasing ``typing`` +e.g. as ``t`` and guarding imports under ``t.TYPE_CHECKING``. + +Closes #7524 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index ea5be2bd6..5dad3be2e 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -1222,9 +1222,7 @@ class VariablesChecker(BaseChecker): # Do not take in account redefined names for the purpose # of type checking.: if any( - isinstance(definition.parent, nodes.If) - and definition.parent.test.as_string() in TYPING_TYPE_CHECKS_GUARDS - for definition in globs[name] + in_type_checking_block(definition) for definition in globs[name] ): continue diff --git a/tests/functional/r/redefined/redefined_outer_name_type_checking.py b/tests/functional/r/redefined/redefined_outer_name_type_checking.py index 562f7ee2d..d452bcdb0 100644 --- a/tests/functional/r/redefined/redefined_outer_name_type_checking.py +++ b/tests/functional/r/redefined/redefined_outer_name_type_checking.py @@ -3,19 +3,27 @@ from __future__ import annotations from typing import TYPE_CHECKING +import typing as t class Cls: - def func(self, stuff: defaultdict): - # This import makes the definition work. + def func(self, stuff: defaultdict, my_deque: deque): + # These imports make the definition work. # pylint: disable=import-outside-toplevel from collections import defaultdict + from collections import deque obj = defaultdict() + obj2 = deque() obj.update(stuff) + obj2.append(my_deque) return obj if TYPE_CHECKING: # This import makes the annotations work. from collections import defaultdict + +if t.TYPE_CHECKING: + # This import makes the annotations work. + from collections import deque -- cgit v1.2.1