Skip to content

Commit 596cde6

Browse files
TH3CHARLieilevkivskyi
authored andcommitted
Support type alias as Literal (#8014)
Resolves #7996
1 parent 355638f commit 596cde6

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

mypy/semanal.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3621,7 +3621,6 @@ def visit_member_expr(self, expr: MemberExpr) -> None:
36213621
type_info = self.type
36223622
elif isinstance(base.node, TypeAlias) and base.node.no_args:
36233623
assert isinstance(base.node.target, ProperType)
3624-
# TODO: support chained aliases.
36253624
if isinstance(base.node.target, Instance):
36263625
type_info = base.node.target.type
36273626

@@ -3969,6 +3968,10 @@ def lookup_qualified(self, name: str, ctx: Context,
39693968
namespace = node.fullname
39703969
elif isinstance(node, PlaceholderNode):
39713970
return sym
3971+
elif isinstance(node, TypeAlias) and node.no_args:
3972+
assert isinstance(node.target, ProperType)
3973+
if isinstance(node.target, Instance):
3974+
nextsym = node.target.type.get(part)
39723975
else:
39733976
if isinstance(node, Var):
39743977
typ = get_proper_type(node.type)

test-data/unit/check-literal.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3149,3 +3149,17 @@ err_code = -TWO
31493149
if bool():
31503150
err_code = -THREE
31513151
[builtins fixtures/float.pyi]
3152+
3153+
[case testAliasForEnumTypeAsLiteral]
3154+
from typing_extensions import Literal
3155+
from enum import Enum
3156+
3157+
class Foo(Enum):
3158+
A = 1
3159+
3160+
F = Foo
3161+
3162+
x: Literal[Foo.A]
3163+
y: Literal[F.A]
3164+
reveal_type(x) # N: Revealed type is 'Literal[__main__.Foo.A]'
3165+
reveal_type(y) # N: Revealed type is 'Literal[__main__.Foo.A]'

test-data/unit/check-type-aliases.test

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -632,3 +632,24 @@ except E as e:
632632
reveal_type(e) # N: Revealed type is '__main__.E'
633633
[builtins fixtures/exception.pyi]
634634
[out]
635+
636+
[case testNestedClassOnAliasAsType]
637+
class Out:
638+
class In:
639+
class Inner:
640+
pass
641+
642+
O = Out
643+
I = Out.In
644+
OI = O.In
645+
A = Out
646+
B = A
647+
648+
w: O.In
649+
x: I.Inner
650+
y: OI.Inner
651+
z: B.In
652+
reveal_type(w) # N: Revealed type is '__main__.Out.In'
653+
reveal_type(x) # N: Revealed type is '__main__.Out.In.Inner'
654+
reveal_type(y) # N: Revealed type is '__main__.Out.In.Inner'
655+
reveal_type(z) # N: Revealed type is '__main__.Out.In'

0 commit comments

Comments
 (0)