Skip to content

Commit

Permalink
Do not allow type[] to contain Literal types
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn committed Dec 10, 2024
1 parent 1497407 commit 7c31a94
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
6 changes: 3 additions & 3 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
5 changes: 3 additions & 2 deletions mypy/types_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
TypeVarType,
UnionType,
UnpackType,
LiteralType,
flatten_nested_unions,
get_proper_type,
get_proper_types,
Expand Down Expand Up @@ -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

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[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]

0 comments on commit 7c31a94

Please sign in to comment.