Skip to content

Commit 161ee24

Browse files
authored
Improve annotated support with non types (python#9625)
Closes python#9315. This PR aims to support Annotated to create type aliases when passing a non type as annotation, like this: ```python class Meta: ... x = Annotated[int, Meta()] ```
1 parent 0fb671c commit 161ee24

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

mypy/exprtotype.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from typing import Optional
44

55
from mypy.nodes import (
6-
Expression, NameExpr, MemberExpr, IndexExpr, TupleExpr, IntExpr, FloatExpr, UnaryExpr,
6+
Expression, NameExpr, MemberExpr, IndexExpr, RefExpr, TupleExpr, IntExpr, FloatExpr, UnaryExpr,
77
ComplexExpr, ListExpr, StrExpr, BytesExpr, UnicodeExpr, EllipsisExpr, CallExpr,
88
get_member_expr_fullname
99
)
@@ -61,7 +61,17 @@ def expr_to_unanalyzed_type(expr: Expression, _parent: Optional[Expression] = No
6161
args = expr.index.items
6262
else:
6363
args = [expr.index]
64-
base.args = tuple(expr_to_unanalyzed_type(arg, expr) for arg in args)
64+
65+
if isinstance(expr.base, RefExpr) and expr.base.fullname in [
66+
'typing.Annotated', 'typing_extensions.Annotated'
67+
]:
68+
# TODO: this is not the optimal solution as we are basically getting rid
69+
# of the Annotation definition and only returning the type information,
70+
# losing all the annotations.
71+
72+
return expr_to_unanalyzed_type(args[0], expr)
73+
else:
74+
base.args = tuple(expr_to_unanalyzed_type(arg, expr) for arg in args)
6575
if not base.args:
6676
base.empty_tuple_index = True
6777
return base

test-data/unit/check-annotated.test

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,13 @@ Alias = Annotated[Union[T, str], ...]
116116
x: Alias[int]
117117
reveal_type(x) # N: Revealed type is 'Union[builtins.int, builtins.str]'
118118
[builtins fixtures/tuple.pyi]
119+
120+
[case testAnnotatedSecondParamNonType]
121+
from typing_extensions import Annotated
122+
123+
class Meta:
124+
...
125+
126+
x = Annotated[int, Meta()]
127+
reveal_type(x) # N: Revealed type is 'def () -> builtins.int'
128+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy