Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't always require typing.Generic as a base for partially parametrized models #7119

Merged
merged 1 commit into from
Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion pydantic/_internal/_model_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ def wrapped_model_post_init(self: BaseModel, __context: Any) -> None:
if __pydantic_generic_metadata__:
cls.__pydantic_generic_metadata__ = __pydantic_generic_metadata__
else:
parameters = getattr(cls, '__parameters__', ())
parent_parameters = getattr(cls, '__pydantic_generic_metadata__', {}).get('parameters', ())
parameters = getattr(cls, '__parameters__', None) or parent_parameters
if parameters and parent_parameters and not all(x in parameters for x in parent_parameters):
combined_parameters = parent_parameters + tuple(x for x in parameters if x not in parent_parameters)
parameters_str = ', '.join([str(x) for x in combined_parameters])
Expand Down
31 changes: 31 additions & 0 deletions tests/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2561,3 +2561,34 @@ class SimpleGenericModel(BaseModel, Generic[T]):

class Concrete(SimpleGenericModel[BaseModel]):
pass


def test_no_generic_base():
T = TypeVar('T')

class A(BaseModel, Generic[T]):
a: T

class B(A[T]):
b: T

class C(B[int]):
pass

assert C(a='1', b='2').model_dump() == {'a': 1, 'b': 2}
with pytest.raises(ValidationError) as exc_info:
C(a='a', b='b')
assert exc_info.value.errors(include_url=False) == [
{
'input': 'a',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
},
{
'input': 'b',
'loc': ('b',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
},
]