From 40730c9e6d8a576b8374527056a3672ab80f7d65 Mon Sep 17 00:00:00 2001 From: sobolevn Date: Wed, 11 Dec 2024 11:10:54 +0300 Subject: [PATCH] Do not allow `type[]` to contain `Literal` types (#18276) Closes https://github.com/python/mypy/issues/18196 --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- mypy/typeanal.py | 11 +++++----- mypy/types_utils.py | 25 +++++++++++++++++------ test-data/unit/check-literal.test | 9 ++++++++ test-data/unit/check-recursive-types.test | 5 +++-- 4 files changed, 37 insertions(+), 13 deletions(-) diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 2f85e83bb3c3..bc340c194cdc 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -110,7 +110,7 @@ get_proper_type, has_type_vars, ) -from mypy.types_utils import is_bad_type_type_item +from mypy.types_utils import get_bad_type_type_item from mypy.typevars import fill_typevars T = TypeVar("T") @@ -652,14 +652,15 @@ 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) + bad_item_name = get_bad_type_type_item(item) + if bad_item_name: + self.fail(f'{type_str} can\'t contain "{bad_item_name}"', 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 1cd56eae5835..aaa7d7fba37a 100644 --- a/mypy/types_utils.py +++ b/mypy/types_utils.py @@ -15,6 +15,7 @@ AnyType, CallableType, Instance, + LiteralType, NoneType, Overloaded, ParamSpecType, @@ -75,21 +76,33 @@ def is_invalid_recursive_alias(seen_nodes: set[TypeAlias], target: Type) -> bool return False -def is_bad_type_type_item(item: Type) -> bool: +def get_bad_type_type_item(item: Type) -> str | None: """Prohibit types like Type[Type[...]]. Such types are explicitly prohibited by PEP 484. Also, they cause problems with recursive types like T = Type[T], because internal representation of TypeType item is normalized (i.e. always a proper type). + + Also forbids `Type[Literal[...]]`, because typing spec does not allow it. """ + # TODO: what else cannot be present in `type[...]`? item = get_proper_type(item) if isinstance(item, TypeType): - return True + return "Type[...]" + if isinstance(item, LiteralType): + return "Literal[...]" if isinstance(item, UnionType): - return any( - isinstance(get_proper_type(i), TypeType) for i in flatten_nested_unions(item.items) - ) - return False + items = [ + bad_item + for typ in flatten_nested_unions(item.items) + if (bad_item := get_bad_type_type_item(typ)) is not None + ] + if not items: + return None + if len(items) == 1: + return items[0] + return f"Union[{', '.join(items)}]" + return None def is_union_with_any(tp: Type) -> bool: diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index 2f94b5df0f83..b2d3024d3b44 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[...]" +y: Type[Union[Literal[1], Literal[2]]] # E: Type[...] can't contain "Union[Literal[...], Literal[...]]" +z: Type[Literal[1, 2]] # E: Type[...] can't contain "Union[Literal[...], Literal[...]]" +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/check-recursive-types.test b/test-data/unit/check-recursive-types.test index 4d7af98204fb..a00a31863771 100644 --- a/test-data/unit/check-recursive-types.test +++ b/test-data/unit/check-recursive-types.test @@ -409,8 +409,9 @@ def local() -> None: x: L reveal_type(x) # N: Revealed type is "builtins.list[Union[builtins.int, Any]]" -S = Type[S] # E: Type[...] can't contain another Type[...] -U = Type[Union[int, U]] # E: Type[...] can't contain another Type[...] +S = Type[S] # E: Type[...] can't contain "Type[...]" +U = Type[Union[int, U]] # E: Type[...] can't contain "Union[Type[...], Type[...]]" \ + # E: Type[...] can't contain "Type[...]" x: U reveal_type(x) # N: Revealed type is "Type[Any]"