Skip to content

Commit 40730c9

Browse files
Do not allow type[] to contain Literal types (#18276)
Closes #18196 --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 1497407 commit 40730c9

File tree

4 files changed

+37
-13
lines changed

4 files changed

+37
-13
lines changed

mypy/typeanal.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
get_proper_type,
111111
has_type_vars,
112112
)
113-
from mypy.types_utils import is_bad_type_type_item
113+
from mypy.types_utils import get_bad_type_type_item
114114
from mypy.typevars import fill_typevars
115115

116116
T = TypeVar("T")
@@ -652,14 +652,15 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Typ
652652
# To prevent assignment of 'builtins.type' inferred as 'builtins.object'
653653
# See https://github.com/python/mypy/issues/9476 for more information
654654
return None
655+
type_str = "Type[...]" if fullname == "typing.Type" else "type[...]"
655656
if len(t.args) != 1:
656-
type_str = "Type[...]" if fullname == "typing.Type" else "type[...]"
657657
self.fail(
658-
type_str + " must have exactly one type argument", t, code=codes.VALID_TYPE
658+
f"{type_str} must have exactly one type argument", t, code=codes.VALID_TYPE
659659
)
660660
item = self.anal_type(t.args[0])
661-
if is_bad_type_type_item(item):
662-
self.fail("Type[...] can't contain another Type[...]", t, code=codes.VALID_TYPE)
661+
bad_item_name = get_bad_type_type_item(item)
662+
if bad_item_name:
663+
self.fail(f'{type_str} can\'t contain "{bad_item_name}"', t, code=codes.VALID_TYPE)
663664
item = AnyType(TypeOfAny.from_error)
664665
return TypeType.make_normalized(item, line=t.line, column=t.column)
665666
elif fullname == "typing.ClassVar":

mypy/types_utils.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
AnyType,
1616
CallableType,
1717
Instance,
18+
LiteralType,
1819
NoneType,
1920
Overloaded,
2021
ParamSpecType,
@@ -75,21 +76,33 @@ def is_invalid_recursive_alias(seen_nodes: set[TypeAlias], target: Type) -> bool
7576
return False
7677

7778

78-
def is_bad_type_type_item(item: Type) -> bool:
79+
def get_bad_type_type_item(item: Type) -> str | None:
7980
"""Prohibit types like Type[Type[...]].
8081
8182
Such types are explicitly prohibited by PEP 484. Also, they cause problems
8283
with recursive types like T = Type[T], because internal representation of
8384
TypeType item is normalized (i.e. always a proper type).
85+
86+
Also forbids `Type[Literal[...]]`, because typing spec does not allow it.
8487
"""
88+
# TODO: what else cannot be present in `type[...]`?
8589
item = get_proper_type(item)
8690
if isinstance(item, TypeType):
87-
return True
91+
return "Type[...]"
92+
if isinstance(item, LiteralType):
93+
return "Literal[...]"
8894
if isinstance(item, UnionType):
89-
return any(
90-
isinstance(get_proper_type(i), TypeType) for i in flatten_nested_unions(item.items)
91-
)
92-
return False
95+
items = [
96+
bad_item
97+
for typ in flatten_nested_unions(item.items)
98+
if (bad_item := get_bad_type_type_item(typ)) is not None
99+
]
100+
if not items:
101+
return None
102+
if len(items) == 1:
103+
return items[0]
104+
return f"Union[{', '.join(items)}]"
105+
return None
93106

94107

95108
def is_union_with_any(tp: Type) -> bool:

test-data/unit/check-literal.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2984,3 +2984,12 @@ class C(Base):
29842984
reveal_type(sep) # N: Revealed type is "Union[Literal['a'], Literal['b']]"
29852985
return super().feed_data(sep)
29862986
[builtins fixtures/tuple.pyi]
2987+
2988+
[case testLiteralInsideAType]
2989+
from typing_extensions import Literal
2990+
from typing import Type, Union
2991+
2992+
x: Type[Literal[1]] # E: Type[...] can't contain "Literal[...]"
2993+
y: Type[Union[Literal[1], Literal[2]]] # E: Type[...] can't contain "Union[Literal[...], Literal[...]]"
2994+
z: Type[Literal[1, 2]] # E: Type[...] can't contain "Union[Literal[...], Literal[...]]"
2995+
[builtins fixtures/tuple.pyi]

test-data/unit/check-recursive-types.test

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,8 +409,9 @@ def local() -> None:
409409
x: L
410410
reveal_type(x) # N: Revealed type is "builtins.list[Union[builtins.int, Any]]"
411411

412-
S = Type[S] # E: Type[...] can't contain another Type[...]
413-
U = Type[Union[int, U]] # E: Type[...] can't contain another Type[...]
412+
S = Type[S] # E: Type[...] can't contain "Type[...]"
413+
U = Type[Union[int, U]] # E: Type[...] can't contain "Union[Type[...], Type[...]]" \
414+
# E: Type[...] can't contain "Type[...]"
414415
x: U
415416
reveal_type(x) # N: Revealed type is "Type[Any]"
416417

0 commit comments

Comments
 (0)