diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 2f85e83bb3c34..22da40a1548af 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -652,14 +652,14 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Typ # To prevent assignment of 'builtins.type' inferred as 'builtins.object' # See https://github.com/python/mypy/issues/9476 for more information return None + type_str = "Type[...]" if fullname == "typing.Type" else "type[...]" if len(t.args) != 1: - type_str = "Type[...]" if fullname == "typing.Type" else "type[...]" self.fail( - type_str + " must have exactly one type argument", t, code=codes.VALID_TYPE + f"{type_str} must have exactly one type argument", t, code=codes.VALID_TYPE ) item = self.anal_type(t.args[0]) if is_bad_type_type_item(item): - self.fail("Type[...] can't contain another Type[...]", t, code=codes.VALID_TYPE) + self.fail(f'{type_str} can\'t contain "{item}"', t, code=codes.VALID_TYPE) item = AnyType(TypeOfAny.from_error) return TypeType.make_normalized(item, line=t.line, column=t.column) elif fullname == "typing.ClassVar": diff --git a/mypy/types_utils.py b/mypy/types_utils.py index 1cd56eae5835c..1f3483193a757 100644 --- a/mypy/types_utils.py +++ b/mypy/types_utils.py @@ -26,6 +26,7 @@ TypeVarType, UnionType, UnpackType, + LiteralType, flatten_nested_unions, get_proper_type, get_proper_types, @@ -83,11 +84,11 @@ def is_bad_type_type_item(item: Type) -> bool: TypeType item is normalized (i.e. always a proper type). """ item = get_proper_type(item) - if isinstance(item, TypeType): + if isinstance(item, (TypeType, LiteralType)): return True if isinstance(item, UnionType): return any( - isinstance(get_proper_type(i), TypeType) for i in flatten_nested_unions(item.items) + is_bad_type_type_item(typ) for typ in flatten_nested_unions(item.items) ) return False diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index 2f94b5df0f83c..cc9abf91da5e7 100644 --- a/test-data/unit/check-literal.test +++ b/test-data/unit/check-literal.test @@ -2984,3 +2984,12 @@ class C(Base): reveal_type(sep) # N: Revealed type is "Union[Literal['a'], Literal['b']]" return super().feed_data(sep) [builtins fixtures/tuple.pyi] + +[case testLiteralInsideAType] +from typing_extensions import Literal +from typing import Type, Union + +x: Type[Literal[1]] # E: Type[...] can't contain "Literal[1]" +y: Type[Union[Literal[1], Literal[2]]] # E: Type[...] can't contain "Union[Literal[1], Literal[2]]" +z: Type[Literal[1, 2]] # E: Type[...] can't contain "Union[Literal[1], Literal[2]]" +[builtins fixtures/tuple.pyi]