Skip to content

default_factory is called with missing validated_data if validation of prior field fails #11358

Open
pydantic/pydantic-core
#1623
@hassec

Description

@hassec

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The below code will crash with the following error.

Traceback (most recent call last):
  File "...", line 9, in <module>
    model = Model(a="abc")
            ^^^^^^^^^^^^^^
  File "/.../.venv/lib/python3.12/site-packages/pydantic/main.py", line 214, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../test.py", line 6, in <lambda>
    b: int = Field(default_factory=lambda data: 2 * data["a"])
                                                    ~~~~^^^^^
KeyError: 'a'

I think the problem is that the error from the failed validation of a: int = "abc" isn't immediately raised, and then the call to the default_factory is done with a dictionary that doesn't have the expected keys.

The resulting error is then not really helpful to a user as the KeyError is just a symptom when the actual cause would be the ValidationError that now isn't reported.

Example Code

from pydantic import BaseModel, Field


class Model(BaseModel):
    a: int = 1
    b: int = Field(default_factory=lambda data: 2 * data["a"])


model = Model(a="abc")

Python, Pydantic & OS Version

pydantic version: 2.10.3
        pydantic-core version: 2.27.1
          pydantic-core build: profile=release pgo=false
                 install path: /Users/chasse/.../.venv/lib/python3.12/site-packages/pydantic
               python version: 3.12.6 (main, Sep  9 2024, 21:36:32) [Clang 18.1.8 ]
                     platform: macOS-15.3-arm64-arm-64bit
             related packages: typing_extensions-4.12.2
                       commit: unknown

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions