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

Pydantic Generic Basemodel Validation Error #9348

Open
1 task done
oliver-helix opened this issue Apr 30, 2024 · 2 comments
Open
1 task done

Pydantic Generic Basemodel Validation Error #9348

oliver-helix opened this issue Apr 30, 2024 · 2 comments
Labels
bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation

Comments

@oliver-helix
Copy link

oliver-helix commented Apr 30, 2024

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Pydantic Generic BaseModels fails unexpectedly when validating python instances but succeeds when validating the same data as a dictionary.

Example Code

from typing import Generic, TypeVar

from pydantic import BaseModel

U = TypeVar("U")


class M1(BaseModel, Generic[U]):
    a: list[U]
    b: list[U]


class M2(BaseModel):
    a: str
    m1: M1[int]


# works
m2 = M2.model_validate(
    {
        "a": "s",
        "m1": {
            "a": [1],
            "b": [2]
        }
    }
)

# does not work
m2 = M2(
    a="s",
    m1=M1(
        a=[1],
        b=[2]
    )
)  # fails :(


# does not work
m2 = M2.model_validate(
    dict(
        a="s",
        m1=M1(
            a=[1],
            b=[2]
        )
    )
)

Python, Pydantic & OS Version

pydantic version: 2.7.1
        pydantic-core version: 2.18.2
          pydantic-core build: profile=release pgo=true
                 install path: /Users/.../.venv/lib/python3.11/site-packages/pydantic
               python version: 3.11.8 (main, Feb  6 2024, 21:21:21) [Clang 15.0.0 (clang-1500.1.0.2.5)]
                     platform: macOS-14.4.1-arm64-arm-64bit
             related packages: typing_extensions-4.11.0
                       commit: unknown
@oliver-helix oliver-helix added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Apr 30, 2024
@aaraney
Copy link
Contributor

aaraney commented Apr 30, 2024

This doesn't look like a bug. It looks like you didn't parametrize the M1 instance with a type. So, constructing M2 is not failing, it's the construction of M1 that is failing.

m2 = M2(
    a="s",
    m1=M1( # missing generic type
        a=[1],
        b=[2]
    )
)  # fails :(

# this works

m2 = M2(
    a="s",
    m1=M1[int](
        a=[1],
        b=[2]
    )
)

@aaraney
Copy link
Contributor

aaraney commented Apr 30, 2024

Seems like a duplicate of #8071

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation
Projects
None yet
Development

No branches or pull requests

2 participants