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

Returning instance from @model_validate(mode="before") raises model_type validation error #9336

Open
1 task done
nilsso opened this issue Apr 27, 2024 · 2 comments
Open
1 task done
Labels
bug V2 Bug related to Pydantic V2
Milestone

Comments

@nilsso
Copy link

nilsso commented Apr 27, 2024

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Returning a model instance from a @model_validate(mode="before") decorated method raises ValidationError.

Example Code

from typing import Any
from pydantic import BaseModel, model_validator

class Foo(BaseModel):
    a: int
    b: int

    @model_validator(mode="before")
    @classmethod
    def _validate(cls, v: Any) -> Any:
        if isinstance(v, str):
            a, b = v.split("-")
            return Foo(a=int(a), b=int(b))
        return v

print(Foo.model_validate("1-2"))
Traceback (most recent call last):
  File "/Users/.../test.py", line 19, in <module>
    print(Foo.model_validate("1-2"))
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/.../.pyenv/versions/3.12.1/lib/python3.12/site-packages/pydantic/main.py", line 509, in model_validate
    return cls.__pydantic_validator__.validate_python(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for Foo
  Input should be a valid dictionary or instance of Foo [type=model_type, input_value=Foo(a=1, b=2), input_type=Foo]
    For further information visit https://errors.pydantic.dev/2.6/v/model_type

As a work around, taking from #7292 (comment)

class Foo(BaseModel):
    a: int
    b: int

    @model_validator(mode="before")
    @classmethod
    def _validate(cls, v: Any) -> Any:
        if isinstance(v, str):
            a, b = v.split("-")
            return Foo(a=int(a), b=int(b)).model_dump()
            # or return {"a": int(a), "b": int(b)}
        return v

Python, Pydantic & OS Version

pydantic version: 2.6.4
        pydantic-core version: 2.16.3
          pydantic-core build: profile=release pgo=true
                 install path: /Users/.../.pyenv/versions/3.12.1/lib/python3.12/site-packages/pydantic
               python version: 3.12.1 (main, Jan  3 2024, 13:12:52) [Clang 15.0.0 (clang-1500.1.0.2.5)]
                     platform: macOS-14.0-arm64-arm-64bit
             related packages: pyright-1.1.350 typing_extensions-4.10.0
                       commit: unknown
@nilsso nilsso added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Apr 27, 2024
@nilsso nilsso changed the title Returning instance from @model_validate(mode="before") breaks validation Returning instance from @model_validate(mode="before") raises model_type validation error Apr 27, 2024
@sydney-runkle sydney-runkle added this to the v2.8.0 milestone Apr 28, 2024
@sydney-runkle
Copy link
Member

@nilsso,

Thanks very much for reporting this. Definitely a bug we want to fix for v2.8.0.

Here's an odd reproduction:

from typing import Any
from pydantic import BaseModel, ConfigDict, model_validator


class Foo(BaseModel):
    a: int
    b: int

    @model_validator(mode="before")
    @classmethod
    def _validate(cls, v: Any) -> Any:
        if isinstance(v, str):
            a, b = v.split("-")
            return Foo(a=int(a), b=int(b))
        return v

print(repr(Foo.model_validate({"a": 1, "b": 2})))
#> Foo(a=1, b=2)
print(repr(Foo.model_validate(Foo(a=1, b=2))))
#> Foo(a=1, b=2)
print(repr(Foo.model_validate("1-2", from_attributes=True)))
#> Foo(a=1, b=2)
print(repr(Foo.model_validate("1-2", from_attributes=False)))
"""
pydantic_core._pydantic_core.ValidationError: 1 validation error for Foo
  Input should be a valid dictionary or instance of Foo [type=model_type, input_value=Foo(a=1, b=2), input_type=Foo]
    For further information visit https://errors.pydantic.dev/2.7/v/model_type
"""

@sydney-runkle sydney-runkle removed the pending Awaiting a response / confirmation label Apr 28, 2024
@davidhewitt
Copy link
Contributor

Moving over from #7292 -

Looking at the "bug" here, the problem is that the "before" validator is running as a wrapper around the model-fields schema, not around the outer model schema. So the "before" validator is required to return a set of fields (i.e. a dictionary), not a complete model.

Potentially the schema needs to be changed so that the before validator runs before the whole "model" schema. I'm not sure what other stuff breaks if we do that. Needs further investigation.

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
Projects
None yet
Development

No branches or pull requests

3 participants