From 333e4c137dcb20f89071698beb9220b21176f97a Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Thu, 14 Nov 2019 10:06:15 +0100 Subject: [PATCH] Allow import aliases to exempt ``import-error`` when used in type annotations. Close #3178 --- ChangeLog | 4 ++++ pylint/checkers/variables.py | 8 ++++++-- tests/functional/u/unused_typing_imports.py | 9 ++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/ChangeLog b/ChangeLog index 3a4665195d..9174b2ed38 100644 --- a/ChangeLog +++ b/ChangeLog @@ -16,6 +16,10 @@ Release date: TBA Close #3235 +* Allow import aliases to exempt ``import-error`` when used in type annotations. + + Close #3178 + * ``Ellipsis` is exempted from ``multiple-statements`` for function overloads. Close #3224 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index dbd8c23c63..dc1f99be45 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -1879,6 +1879,10 @@ def _check_imports(self, not_consumed): continue checked.add(real_name) + is_type_annotation_import = ( + imported_name in self._type_annotation_names + or as_name in self._type_annotation_names + ) if isinstance(stmt, astroid.Import) or ( isinstance(stmt, astroid.ImportFrom) and not stmt.modname ): @@ -1889,7 +1893,7 @@ def _check_imports(self, not_consumed): # because they can be imported for exporting. continue - if imported_name in self._type_annotation_names: + if is_type_annotation_import: # Most likely a typing import if it wasn't used so far. continue @@ -1912,7 +1916,7 @@ def _check_imports(self, not_consumed): # __future__ import in another module. continue - if imported_name in self._type_annotation_names: + if is_type_annotation_import: # Most likely a typing import if it wasn't used so far. continue diff --git a/tests/functional/u/unused_typing_imports.py b/tests/functional/u/unused_typing_imports.py index c0a2f49863..c143bb18ec 100644 --- a/tests/functional/u/unused_typing_imports.py +++ b/tests/functional/u/unused_typing_imports.py @@ -7,6 +7,7 @@ import re import typing +from collections import Counter as CollectionCounter from collections import defaultdict from datetime import datetime from typing import ( @@ -74,5 +75,11 @@ def magic(alpha, beta, gamma): def unused_assignment_import(): - foo_or_bar = defaultdict(int) # type: defaultdict + foo_or_bar = 42 # type: defaultdict return foo_or_bar + + +def unused_reassigned_import(counter): + # type: (CollectionCounter) -> int + print(counter) + return 42