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

Current field value is not displayed in after field validator #8126

Open
1 task done
MaxHalford opened this issue Nov 15, 2023 · 5 comments · May be fixed by pydantic/pydantic-core#1278
Open
1 task done

Current field value is not displayed in after field validator #8126

MaxHalford opened this issue Nov 15, 2023 · 5 comments · May be fixed by pydantic/pydantic-core#1278
Assignees
Labels
bug V2 Bug related to Pydantic V2

Comments

@MaxHalford
Copy link

MaxHalford commented Nov 15, 2023

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

I have a before field validator which populates a field based on another field. I then have an after field validator which checks the obtained value. The resolution order of these validators is correct. The issue I see is that in the error message, the input_value displays the current value of the field, it instead displays what I assume is the starting value.

This isn't a blocking issue. But I believe modifying the message to display the current value of the field would be more useful.

I'm happy to provide more details if needed :)

Example Code

Here's the MRE:

import pydantic
import typing
from typing_extensions import Annotated
from pydantic import BaseModel, ValidationInfo, field_validator
from pydantic.dataclasses import dataclass


class Base(BaseModel):
    raw: str
    norm: typing.Any | None = None

    @field_validator('norm')
    def normalize_raw_if_no_norm(cls, norm: str | None, info: ValidationInfo):
        if norm is None:
            norm = cls.normalize_raw(info['model'].raw)
        return norm

@dataclass
class Weight:
    raw: str | None = None
    norm: Annotated[typing.Any | None, pydantic.Field(validate_default=True)] = None

    @pydantic.field_validator("norm", mode="before")
    def normalize_raw_if_no_norm(cls, norm: str | None, info: ValidationInfo):
        print("normalize_raw_if_no_norm")
        if norm is None:
            if (raw := info.data.get("raw")):
                norm = cls.normalize_raw(info.data["raw"])
            else:
                raise ValueError("Either raw or norm has to be provided")
        return norm

    @pydantic.field_validator("norm")
    def check_positive(cls, norm):
        print(norm)
        assert norm >= 0, "Weight has to be positive"
        return norm

    @classmethod
    def normalize_raw(cls, raw: str):
        return float(raw)

Weight(raw='-32')

Here's the exception:

ValidationError: 1 validation error for Weight
norm
  Assertion failed, Weight has to be positive [type=assertion_error, input_value=None, input_type=NoneType]
    For further information visit https://errors.pydantic.dev/2.5/v/assertion_error

As you can see, the input_value is None and not -32.0. This is what I would expect:

ValidationError: 1 validation error for Weight
norm
  Assertion failed, Weight has to be positive [type=assertion_error, input_value=-32.0, input_type=float]
    For further information visit https://errors.pydantic.dev/2.5/v/assertion_error

Python, Pydantic & OS Version

pydantic version: 2.5.0
        pydantic-core version: 2.14.1
          pydantic-core build: profile=release pgo=true
                 install path: /Users/max/Library/Caches/pypoetry/virtualenvs/vera-aGmBzZyk-py3.10/lib/python3.10/site-packages/pydantic
               python version: 3.10.8 (main, Nov 10 2022, 15:09:18) [Clang 14.0.0 (clang-1400.0.29.102)]
                     platform: macOS-14.0-arm64-arm-64bit
             related packages: fastapi-0.100.0 typing_extensions-4.6.3
@MaxHalford MaxHalford added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Nov 15, 2023
@sydney-runkle sydney-runkle added change Suggested alteration to pydantic, not a new feature nor a bug and removed bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Nov 15, 2023
@sydney-runkle sydney-runkle self-assigned this Nov 15, 2023
@sydney-runkle sydney-runkle added bug V2 Bug related to Pydantic V2 and removed change Suggested alteration to pydantic, not a new feature nor a bug labels Nov 17, 2023
@sydney-runkle
Copy link
Member

Hi @MaxHalford,

Thanks for reporting this. This does look like a bug. I'm guessing it might be on the pydantic-core end of things. Let's see what @davidhewitt thinks on Monday!

@MaxHalford
Copy link
Author

My bad: I didn't take the time to think if this pertained to pydantic or pydantic-core.

Have a good weekend!

@sydney-runkle
Copy link
Member

@MaxHalford, no worries at all! Thanks for bringing the issue to our attention 😄.

@giovanni-bellini-argo
Copy link

any news on this issue?

@davidhewitt
Copy link
Contributor

So I've identified why the result happens as it does, and I've opened pydantic/pydantic-core#1278 which would create the behaviour suggested here. I need to reflect further on what the repercussions of that change might be.

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

Successfully merging a pull request may close this issue.

4 participants