You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Indeed this is confusing. I think it's best to directly raise a validation error if the default factory is called (and it takes the data argument) and if at least one validation of a previous field failed.
If this doesn't make it into 2.11.0, we will still be able to include it in a patch release as a backport. Self note: this should also be fixed for field validators accessing the data.
Initial Checks
Description
The below code will crash with the following error.
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 thedefault_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 theValidationError
that now isn't reported.Example Code
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: