From d2ab3ec801a0b280ab0fbc66f5afbe3acf6f3701 Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Tue, 5 Jan 2021 00:05:29 +0200 Subject: 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. --- pyflakes/checker.py | 13 +++++++++++++ pyflakes/test/test_type_annotations.py | 15 +++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/pyflakes/checker.py b/pyflakes/checker.py index 0d65506..095397b 100644 --- a/pyflakes/checker.py +++ b/pyflakes/checker.py @@ -1680,6 +1680,19 @@ class Checker(object): with self._enter_annotation(AnnotationState.STRING): self.handleNode(node.args[0], node) + elif _is_typing(node.func, 'TypeVar', self.scopeStack): + # TypeVar("T", "int", "str") + for arg in node.args[1:]: + if isinstance(arg, ast.Str): + with self._enter_annotation(): + self.handleNode(arg, node) + + # TypeVar("T", bound="str") + for keyword in node.keywords: + if keyword.arg == 'bound' and isinstance(keyword.value, ast.Str): + with self._enter_annotation(): + self.handleNode(keyword.value, node) + self.handleChildren(node) def _handle_percent_format(self, node): diff --git a/pyflakes/test/test_type_annotations.py b/pyflakes/test/test_type_annotations.py index d5a3e08..409238b 100644 --- a/pyflakes/test/test_type_annotations.py +++ b/pyflakes/test/test_type_annotations.py @@ -524,6 +524,21 @@ class TestTypeAnnotations(TestCase): maybe_int = tsac('Maybe[int]', 42) """) + def test_quoted_TypeVar_constraints(self): + self.flakes(""" + from typing import TypeVar, Optional + + T = TypeVar('T', 'str', 'Optional[int]', bytes) + """) + + def test_quoted_TypeVar_bound(self): + self.flakes(""" + from typing import TypeVar, Optional, List + + T = TypeVar('T', bound='Optional[int]') + S = TypeVar('S', int, bound='List[int]') + """) + @skipIf(version_info < (3,), 'new in Python 3') def test_literal_type_typing(self): self.flakes(""" -- cgit v1.2.1