Skip to content

Commit 7c31a94

Browse files
committed
Do not allow type[] to contain Literal types
1 parent 1497407 commit 7c31a94

File tree

3 files changed

+15
-5
lines changed

3 files changed

+15
-5
lines changed

mypy/typeanal.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -652,14 +652,14 @@ 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])
661661
if is_bad_type_type_item(item):
662-
self.fail("Type[...] can't contain another Type[...]", t, code=codes.VALID_TYPE)
662+
self.fail(f'{type_str} can\'t contain "{item}"', t, code=codes.VALID_TYPE)
663663
item = AnyType(TypeOfAny.from_error)
664664
return TypeType.make_normalized(item, line=t.line, column=t.column)
665665
elif fullname == "typing.ClassVar":

mypy/types_utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
TypeVarType,
2727
UnionType,
2828
UnpackType,
29+
LiteralType,
2930
flatten_nested_unions,
3031
get_proper_type,
3132
get_proper_types,
@@ -83,11 +84,11 @@ def is_bad_type_type_item(item: Type) -> bool:
8384
TypeType item is normalized (i.e. always a proper type).
8485
"""
8586
item = get_proper_type(item)
86-
if isinstance(item, TypeType):
87+
if isinstance(item, (TypeType, LiteralType)):
8788
return True
8889
if isinstance(item, UnionType):
8990
return any(
90-
isinstance(get_proper_type(i), TypeType) for i in flatten_nested_unions(item.items)
91+
is_bad_type_type_item(typ) for typ in flatten_nested_unions(item.items)
9192
)
9293
return False
9394

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[1]"
2993+
y: Type[Union[Literal[1], Literal[2]]] # E: Type[...] can't contain "Union[Literal[1], Literal[2]]"
2994+
z: Type[Literal[1, 2]] # E: Type[...] can't contain "Union[Literal[1], Literal[2]]"
2995+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)