Skip to content

Commit d2ab3ec

Browse files
authored
Fix quoted type annotations in typing.TypeVar contexts (#534)
TypeVar has such contexts in the positional arguments (for constraints) and in the `bound` keyword argument.
1 parent 0e4194b commit d2ab3ec

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

pyflakes/checker.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,19 @@ def CALL(self, node):
16801680
with self._enter_annotation(AnnotationState.STRING):
16811681
self.handleNode(node.args[0], node)
16821682

1683+
elif _is_typing(node.func, 'TypeVar', self.scopeStack):
1684+
# TypeVar("T", "int", "str")
1685+
for arg in node.args[1:]:
1686+
if isinstance(arg, ast.Str):
1687+
with self._enter_annotation():
1688+
self.handleNode(arg, node)
1689+
1690+
# TypeVar("T", bound="str")
1691+
for keyword in node.keywords:
1692+
if keyword.arg == 'bound' and isinstance(keyword.value, ast.Str):
1693+
with self._enter_annotation():
1694+
self.handleNode(keyword.value, node)
1695+
16831696
self.handleChildren(node)
16841697

16851698
def _handle_percent_format(self, node):

pyflakes/test/test_type_annotations.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,21 @@ def test_quoted_type_cast_renamed_import(self):
524524
maybe_int = tsac('Maybe[int]', 42)
525525
""")
526526

527+
def test_quoted_TypeVar_constraints(self):
528+
self.flakes("""
529+
from typing import TypeVar, Optional
530+
531+
T = TypeVar('T', 'str', 'Optional[int]', bytes)
532+
""")
533+
534+
def test_quoted_TypeVar_bound(self):
535+
self.flakes("""
536+
from typing import TypeVar, Optional, List
537+
538+
T = TypeVar('T', bound='Optional[int]')
539+
S = TypeVar('S', int, bound='List[int]')
540+
""")
541+
527542
@skipIf(version_info < (3,), 'new in Python 3')
528543
def test_literal_type_typing(self):
529544
self.flakes("""

0 commit comments

Comments
 (0)