-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Description
Initial Checks
- I confirm that I'm using Pydantic V2
Description
When nesting generic models, unless the inner model's type is also concretely typed the outer validation fails.
It's trivial to fix for this simple example, but for more complex/dynamic cases I haven't found any way of getting round this without coming up with something outside of pydantic.
Runtime type is 'Inner'
Traceback (most recent call last):
File "repo/ptest.py", line 41, in <module>
fails = Holder[int](inner=inferred)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "repo/venv/lib/python3.11/site-packages/pydantic/main.py", line 164, in __init__
__pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Holder[int]
inner
Input should be a valid dictionary or instance of Inner[int] [type=model_type, input_value=Inner(inner=1), input_type=Inner]
For further information visit https://errors.pydantic.dev/2.4/v/model_type
Example Code
import typing as tp
from pydantic import BaseModel
T = tp.TypeVar("T")
class Inner(BaseModel, tp.Generic[T]):
inner: T
class Holder(BaseModel, tp.Generic[T]):
inner: Inner[T]
inferred = Inner(inner=1)
tp.reveal_type(inferred) # Type of "inferred" is "Inner[int]" (Pylance)
works = Holder[int](inner=Inner[int](inner=1))
fails = Holder[int](inner=inferred)
Python, Pydantic & OS Version
pydantic version: 2.4.2
pydantic-core version: 2.10.1
pydantic-core build: profile=release pgo=false
install path: repo/venv/lib/python3.11/site-packages/pydantic
python version: 3.11.6 (main, Oct 2 2023, 13:45:54) [Clang 15.0.0 (clang-1500.0.40.1)]
platform: macOS-14.1-arm64-arm-64bit
related packages: mypy-1.6.1 pyright-1.1.335 typing_extensions-4.8.0 email-validator-2.1.0 fastapi-0.103.2
h4l, failable and mbbyn