Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix function containing PEP 593 Annotated with a string literal second arg causing 'Name "x" is not defined" error #10777

Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
15 changes: 11 additions & 4 deletions test-data/unit/check-annotated.test
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,26 @@ x = Annotated[int, Meta()]
reveal_type(x) # N: Revealed type is "def () -> builtins.int"
[builtins fixtures/tuple.pyi]

[case testAnnotatedStringLiteralInFunc]
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you reveal_type() this one too?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And maybe also add a testcase with a generic function, so we can confirm that a typevar in the first arg to Annotated is still picked up correctly.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JelleZijlstra I added a case. Is it correct?

def f3(a: Annotated["notdefined", "metadata"]): # E: Name "notdefined" is not defined
pass

[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]