Skip to content

Commit 40b6b9b

Browse files
Fix function containing PEP 593 Annotated with a string literal second 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>
1 parent eea4c76 commit 40b6b9b

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

mypy/typeanal.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,9 @@ def visit_unbound_type(self, t: UnboundType) -> TypeVarLikeList:
12691269
return []
12701270
elif node and node.fullname in ('typing_extensions.Literal', 'typing.Literal'):
12711271
return []
1272+
elif node and node.fullname in ('typing_extensions.Annotated', 'typing.Annotated'):
1273+
# Don't query the second argument to Annotated for TypeVars
1274+
return self.query_types([t.args[0]])
12721275
else:
12731276
return super().visit_unbound_type(t)
12741277

test-data/unit/check-annotated.test

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,19 +127,33 @@ x = Annotated[int, Meta()]
127127
reveal_type(x) # N: Revealed type is "def () -> builtins.int"
128128
[builtins fixtures/tuple.pyi]
129129

130+
[case testAnnotatedStringLiteralInFunc]
131+
from typing import TypeVar
132+
from typing_extensions import Annotated
133+
def f1(a: Annotated[str, "metadata"]):
134+
pass
135+
reveal_type(f1) # N: Revealed type is "def (a: builtins.str) -> Any"
136+
def f2(a: Annotated["str", "metadata"]):
137+
pass
138+
reveal_type(f2) # N: Revealed type is "def (a: builtins.str) -> Any"
139+
def f3(a: Annotated["notdefined", "metadata"]): # E: Name "notdefined" is not defined
140+
pass
141+
T = TypeVar('T')
142+
def f4(a: Annotated[T, "metatdata"]):
143+
pass
144+
reveal_type(f4) # N: Revealed type is "def [T] (a: T`-1) -> Any"
145+
[builtins fixtures/tuple.pyi]
146+
130147
[case testSliceAnnotated39]
131148
# flags: --python-version 3.9
132149
from typing_extensions import Annotated
133-
134150
a: Annotated[int, 1:2]
135151
reveal_type(a) # N: Revealed type is "builtins.int"
136-
137152
[builtins fixtures/tuple.pyi]
153+
138154
[case testSliceAnnotated38]
139155
# flags: --python-version 3.8
140156
from typing_extensions import Annotated
141-
142157
a: Annotated[int, 1:2]
143158
reveal_type(a) # N: Revealed type is "builtins.int"
144-
145159
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)