Skip to content

Commit

Permalink
Do not allow type[] to contain Literal types (python#18276)
Browse files Browse the repository at this point in the history
Closes python#18196

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
sobolevn and pre-commit-ci[bot] authored Dec 11, 2024
1 parent 1497407 commit 40730c9
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 13 deletions.
11 changes: 6 additions & 5 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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":
Expand Down
25 changes: 19 additions & 6 deletions mypy/types_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
AnyType,
CallableType,
Instance,
LiteralType,
NoneType,
Overloaded,
ParamSpecType,
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 9 additions & 0 deletions test-data/unit/check-literal.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
5 changes: 3 additions & 2 deletions test-data/unit/check-recursive-types.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]"

Expand Down

0 comments on commit 40730c9

Please sign in to comment.