-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
Subclass to a class inheriting from GenericModel - no validation at instantiation #1229
Comments
humm, not sure. @dmontagu any idea whether we want to fix this? |
It works all right if you repeat the from typing import TypeVar, Generic
import pydantic
from pydantic.main import ModelMetaclass
from pydantic.generics import GenericModel
import pytest
def test_case():
TypeX = TypeVar('TypeX')
SampleTypeX = list
class MyBaseClass(GenericModel, Generic[TypeX]):
X: TypeX
class Example(MyBaseClass[TypeX], Generic[TypeX]):
pass
Example[SampleTypeX](X=[0, 1, 2])
with pytest.raises(pydantic.error_wrappers.ValidationError):
Example[SampleTypeX](X=1)
test_case() @Esadruhn does this help? I think it might make sense to refactor this more fully at some point for better compatibility with the typing library, though there are challenges with that as noted in other issues (namely, the typing package has been rather aggressive about keeping certain functionality private/internal use only). |
Thank you for the answer, it works fine ! Pending a refactor, would it be possible to document this ? |
Yes, I think adding docs about it is a good idea. If you wanted to submit a PR adding the docs that would be awesome, otherwise I'll get to it eventually. |
Thanks, I'll see if I can do it in the next few days. I really like the inclusion of actual Python scripts in the doc !
error in validation_decorator_parameter_types.py: Traceback (most recent call last):
pydantic/docs/examples/validation_decorator_parameter_types.py", line 20
`def pos_only(a: int, b: int = 2, /) -> str: # python 3.8 only` |
Yes, that's expected, I should be able to build in a check that avoids executing that example for earlier versions. |
Documentation added in #1249 to explain how to properly inherit from a |
Bug
There is a bug, or maybe a feature request, with inheritance and Generics.
If I define a class that inherits from GenericModel and a subclass, then when I instanciate the subclass there is no check on the generic type.
From what I saw in the code, it is because the checks are done in the metaclass
__new__
method (generics are treated asOptional[Any]
at that point), and the generic type is defined afterwards, in the__getitem__
method.Output of
python -c "import pydantic.utils; print(pydantic.utils.version_info())"
:This test passes - no inheritance
Failed test case - inheritance
The text was updated successfully, but these errors were encountered: