Skip to content

Commit

Permalink
Fix function containing PEP 593 Annotated with a string literal secon…
Browse files Browse the repository at this point in the history
…d arg causing 'Name "x" is not defined" error (#10777)

Fixes #9868

When analyzing function definitions, mypy attempts to infer type variables. The code which did that also tried to look into the second type arg to `Annotated`, which, if a string literal, resulted in a lookup which may cause a 'Name "x" is not defined" error.

Co-authored-by: 97littleleaf11 <97littleleaf11@users.noreply.github.com>
Co-authored-by: Jingchen Ye <97littleleaf11@gmail.com>
  • Loading branch information
3 people authored Nov 26, 2021
1 parent eea4c76 commit 40b6b9b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
3 changes: 3 additions & 0 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,9 @@ def visit_unbound_type(self, t: UnboundType) -> TypeVarLikeList:
return []
elif node and node.fullname in ('typing_extensions.Literal', 'typing.Literal'):
return []
elif node and node.fullname in ('typing_extensions.Annotated', 'typing.Annotated'):
# Don't query the second argument to Annotated for TypeVars
return self.query_types([t.args[0]])
else:
return super().visit_unbound_type(t)

Expand Down
22 changes: 18 additions & 4 deletions test-data/unit/check-annotated.test
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,33 @@ x = Annotated[int, Meta()]
reveal_type(x) # N: Revealed type is "def () -> builtins.int"
[builtins fixtures/tuple.pyi]

[case testAnnotatedStringLiteralInFunc]
from typing import TypeVar
from typing_extensions import Annotated
def f1(a: Annotated[str, "metadata"]):
pass
reveal_type(f1) # N: Revealed type is "def (a: builtins.str) -> Any"
def f2(a: Annotated["str", "metadata"]):
pass
reveal_type(f2) # N: Revealed type is "def (a: builtins.str) -> Any"
def f3(a: Annotated["notdefined", "metadata"]): # E: Name "notdefined" is not defined
pass
T = TypeVar('T')
def f4(a: Annotated[T, "metatdata"]):
pass
reveal_type(f4) # N: Revealed type is "def [T] (a: T`-1) -> Any"
[builtins fixtures/tuple.pyi]

[case testSliceAnnotated39]
# flags: --python-version 3.9
from typing_extensions import Annotated

a: Annotated[int, 1:2]
reveal_type(a) # N: Revealed type is "builtins.int"

[builtins fixtures/tuple.pyi]

[case testSliceAnnotated38]
# flags: --python-version 3.8
from typing_extensions import Annotated

a: Annotated[int, 1:2]
reveal_type(a) # N: Revealed type is "builtins.int"

[builtins fixtures/tuple.pyi]

0 comments on commit 40b6b9b

Please sign in to comment.