8000 Raise a better error when a generic alias is used inside `type[]` (#1… · pydantic/pydantic@c393317 · GitHub
[go: up one dir, main page]

Skip to content

Commit c393317

Browse files
authored
Raise a better error when a generic alias is used inside type[] (#11088)
1 parent d924a0b commit c393317

File tree

2 files changed

+19
-2
lines changed
Expand file tree

2 files changed

+19
-2
lines changed

pydantic/_internal/_generate_schema.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@
6363
from ..json_schema import JsonSchemaValue
6464
from ..version import version_short
6565
from ..warnings import PydanticDeprecatedSince20
66-
from . import _core_utils, _decorators, _discriminated_union, _known_annotated_metadata, _typing_extra
66+
from . import _core_utils, _decorators, _discriminated_union, _known_annotated_metadata, _repr, _typing_extra
6767
from ._config import ConfigWrapper, ConfigWrapperStack
6868
from ._core_metadata import update_core_metadata
6969
from ._core_utils import (
@@ -1647,7 +1647,12 @@ def _subclass_schema(self, type_: Any) -> core_schema.CoreSchema:
16471647
else:
16481648
if _typing_extra.is_self(type_param):
16491649
type_param = self._resolve_self_type(type_param)
1650-
1650+
if _typing_extra.is_generic_alias(type_param):
1651+
raise PydanticUserError(
1652+
'Subscripting `type[]` with an already parametrized type is not supported. '
1653+
f'Instead of using type[{type_param!r}], use type[{_repr.display_as_type(get_origin(type_param))}].',
1654+
code=None,
1655+
)
16511656
if not inspect.isclass(type_param):
16521657
raise TypeError(f'Expected a class, got {type_param!r}')
16531658
return core_schema.is_subclass_schema(type_param)

tests/test_edge_cases.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
PrivateAttr,
3636
PydanticDeprecatedSince20,
3737
PydanticSchemaGenerationError,
38+
PydanticUserError,
3839
RootModel,
3940
TypeAdapter,
4041
ValidationError,
@@ -1470,6 +1471,17 @@ class Model(BaseModel):
14701471
]
14711472

14721473

1474+
def test_type_on_generic_alias() -> None:
1475+
error_msg = 'Instead of using type[typing.List[int]], use type[list].'
1476+
1477+
with pytest.raises(PydanticUserError) as exc_info:
1478+
1479+
class Model(BaseModel):
1480+
a: Type[List[int]]
1481+
1482+
assert error_msg in exc_info.value.message
1483+
1484+
14731485
def test_type_assign():
14741486
class Parent:
14751487
def echo(self):

0 commit comments

Comments
 (0)
0