diff options
author | Daniƫl van Noord <13665637+DanielNoord@users.noreply.github.com> | 2021-11-25 18:05:32 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-25 18:05:32 +0100 |
commit | fe69c1d5d7b5b51bd35647839ed59bce539ff4b8 (patch) | |
tree | 2457ab06dcd7f53d74bc741e67eb5008767c2100 | |
parent | 8b3ce5576aa4c43484606381dbd3fe95091133bc (diff) | |
download | pylint-git-fe69c1d5d7b5b51bd35647839ed59bce539ff4b8.tar.gz |
Make ``unused-import`` check all ancestors for typing guards (#5316)
-rw-r--r-- | pylint/checkers/variables.py | 15 | ||||
-rw-r--r-- | tests/functional/u/unused/unused_import.py | 4 |
2 files changed, 12 insertions, 7 deletions
diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index cfedb56dd..fa3c0867e 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -63,7 +63,7 @@ import os import re import sys from functools import lru_cache -from typing import DefaultDict, List, Optional, Set, Tuple +from typing import DefaultDict, List, Optional, Set, Tuple, Union import astroid from astroid import nodes @@ -360,12 +360,13 @@ def _assigned_locally(name_node): return any(a.name == name_node.name for a in assign_stmts) -def _is_type_checking_import(node): - parent = node.parent - if not isinstance(parent, nodes.If): - return False - test = parent.test - return test.as_string() in TYPING_TYPE_CHECKS_GUARDS +def _is_type_checking_import(node: Union[nodes.Import, nodes.ImportFrom]) -> bool: + """Check if an import node is guarded by a TYPE_CHECKS guard""" + for ancestor in node.node_ancestors(): + if isinstance(ancestor, nodes.If): + if ancestor.test.as_string() in TYPING_TYPE_CHECKS_GUARDS: + return True + return False def _has_locals_call_after_node(stmt, scope): diff --git a/tests/functional/u/unused/unused_import.py b/tests/functional/u/unused/unused_import.py index 3bf17c6c9..bd624dc76 100644 --- a/tests/functional/u/unused/unused_import.py +++ b/tests/functional/u/unused/unused_import.py @@ -61,3 +61,7 @@ class NonRegr(object): def blop(self): """yo""" print(self, 'blip') + +if TYPE_CHECKING: + if sys.version_info >= (3, 6, 2): + from typing import NoReturn |