Skip to content

Incorrect ValidationInfo.field_name when using type statement #11737

@bblanchon

Description

@bblanchon

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Field validators receive an incorrect value for field_name for fields defined with a type alias made with a type statement.

The following code uses a type alias to reuse a field validator in multiple fields.

from typing import Annotated

from pydantic import AfterValidator, BaseModel, ValidationInfo


def validate_my_field(value: str, info: ValidationInfo):
    print(f"{info.field_name} = {value}")
    return value


type MyField = Annotated[str, AfterValidator(validate_my_field)]


class MyModel(BaseModel):
    field1: MyField
    field2: MyField


MyModel.model_validate(
    {
        "field1": "value1",
        "field2": "value2",
    }
)

However, the input is incorrect:

field1 = value1
field1 = value2

As you can see, the validator function is called twice with field_name set to field1.

Notice that the bug only happens with Python 3.12's type statement but doesn't occur if we use TypeAlias:

MyField: TypeAlias = Annotated[str, AfterValidator(validate_my_field)]

After changing this line, the output is correct:

field1 = value1
field2 = value2

Python, Pydantic & OS Version

             pydantic version: 2.11.3
        pydantic-core version: 2.33.1
          pydantic-core build: profile=release pgo=false
                 install path: E:\Git\throwaways\pydantic-field-name-bug\.venv\Lib\site-packages\pydantic
               python version: 3.12.10 (tags/v3.12.10:0cc8128, Apr  8 2025, 12:21:36) [MSC v.1943 64 bit (AMD64)]
                     platform: Windows-11-10.0.26100-SP0
             related packages: typing_extensions-4.13.2
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions