From 344f6859e9d584309f57d142259fad77a17d11ee Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Tue, 17 Sep 2019 09:58:07 +0200 Subject: [PATCH] Handle redefinitions in case of type checking imports. Close #2834 --- ChangeLog | 4 ++++ pylint/checkers/variables.py | 9 +++++++++ .../r/redefined_outer_name_type_checking.py | 20 +++++++++++++++++++ .../r/redefined_outer_name_type_checking.rc | 2 ++ 4 files changed, 35 insertions(+) create mode 100644 tests/functional/r/redefined_outer_name_type_checking.py create mode 100644 tests/functional/r/redefined_outer_name_type_checking.rc diff --git a/ChangeLog b/ChangeLog index 8c923262d4..da25f1b6bb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -16,6 +16,10 @@ Release date: TBA Close #2540 +* Handle redefinitions in case of type checking imports. + + Close #2834 + * Added a new check, ``consider-using-sys-exit`` This check is emitted when we detect that a quit() or exit() is invoked diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 6bd5d7ff77..e55d32ad15 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -942,6 +942,15 @@ def visit_functiondef(self, node): # It is a __future__ directive, not a symbol. continue + # Do not take in account redefined names for the purpose + # of type checking.: + if any( + isinstance(definition.parent, astroid.If) + and definition.parent.test.as_string() in TYPING_TYPE_CHECKS_GUARDS + for definition in globs[name] + ): + continue + line = definition.fromlineno if not self._is_name_ignored(stmt, name): self.add_message( diff --git a/tests/functional/r/redefined_outer_name_type_checking.py b/tests/functional/r/redefined_outer_name_type_checking.py new file mode 100644 index 0000000000..b708902e0c --- /dev/null +++ b/tests/functional/r/redefined_outer_name_type_checking.py @@ -0,0 +1,20 @@ +# pylint: disable=missing-module-docstring,missing-class-docstring,too-few-public-methods +# pylint: disable=no-self-use,missing-function-docstring +from __future__ import annotations + +from typing import TYPE_CHECKING + + +class Cls: + def func(self, stuff: defaultdict): + # This import makes the definition work. + from collections import defaultdict + + obj = defaultdict() + obj.update(stuff) + return obj + + +if TYPE_CHECKING: + # This import makes the annotations work. + from collections import defaultdict diff --git a/tests/functional/r/redefined_outer_name_type_checking.rc b/tests/functional/r/redefined_outer_name_type_checking.rc new file mode 100644 index 0000000000..a17bb22daf --- /dev/null +++ b/tests/functional/r/redefined_outer_name_type_checking.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.7