Skip to content

Commit 84da8cd

Browse files
authored
support TypeAlias annotations (#679)
For assignments with `TypeAlias` as annotation, handle the value as an annotation also. Avoids incorrectly detecting `Bar` as unused in `x: TypeAlias = 'Bar'`.
1 parent 1fae3de commit 84da8cd

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

pyflakes/checker.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def _is_const_non_singleton(node): # type: (ast.AST) -> bool
128128
return _is_constant(node) and not _is_singleton(node)
129129

130130

131-
def _is_name_or_attr(node, name): # type: (ast.Ast, str) -> bool
131+
def _is_name_or_attr(node, name): # type: (ast.AST, str) -> bool
132132
return (
133133
(isinstance(node, ast.Name) and node.id == name) or
134134
(isinstance(node, ast.Attribute) and node.attr == name)
@@ -2381,9 +2381,13 @@ def EXCEPTHANDLER(self, node):
23812381
def ANNASSIGN(self, node):
23822382
self.handleNode(node.target, node)
23832383
self.handleAnnotation(node.annotation, node)
2384+
# If the assignment has value, handle the *value* now.
23842385
if node.value:
2385-
# If the assignment has value, handle the *value* now.
2386-
self.handleNode(node.value, node)
2386+
# If the annotation is `TypeAlias`, handle the *value* as an annotation.
2387+
if _is_typing(node.annotation, 'TypeAlias', self.scopeStack):
2388+
self.handleAnnotation(node.value, node)
2389+
else:
2390+
self.handleNode(node.value, node)
23872391

23882392
def COMPARE(self, node):
23892393
left = node.left

pyflakes/test/test_type_annotations.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,46 @@ def g(t: 'T'): pass
300300
a: 'a: "A"'
301301
''', m.ForwardAnnotationSyntaxError)
302302

303+
@skipIf(version_info < (3, 6), 'new in Python 3.6')
304+
def test_TypeAlias_annotations(self):
305+
self.flakes("""
306+
from typing_extensions import TypeAlias
307+
from foo import Bar
308+
309+
bar: TypeAlias = Bar
310+
""")
311+
self.flakes("""
312+
from typing_extensions import TypeAlias
313+
from foo import Bar
314+
315+
bar: TypeAlias = 'Bar'
316+
""")
317+
self.flakes("""
318+
from typing_extensions import TypeAlias
319+
from foo import Bar
320+
321+
class A:
322+
bar: TypeAlias = Bar
323+
""")
324+
self.flakes("""
325+
from typing_extensions import TypeAlias
326+
from foo import Bar
327+
328+
class A:
329+
bar: TypeAlias = 'Bar'
330+
""")
331+
self.flakes("""
332+
from typing_extensions import TypeAlias
333+
334+
bar: TypeAlias
335+
""")
336+
self.flakes("""
337+
from typing_extensions import TypeAlias
338+
from foo import Bar
339+
340+
bar: TypeAlias
341+
""", m.UnusedImport)
342+
303343
@skipIf(version_info < (3, 6), 'new in Python 3.6')
304344
def test_annotating_an_import(self):
305345
self.flakes('''

0 commit comments

Comments
 (0)