Execution order of model_validators reversed from root_validators in v1 #7434
sarahandromeda
started this conversation in
Pydantic V2
Replies: 1 comment
-
This issue is still occurring in v2.6.4. Runs in declared order if mode='after', but in reverse order if mode='before'. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi all!! So we've been using pydantic at work long enough that we had to migrate over to v2 after writing all our models in v1.
We used
root_validator
in v1 so we swapped those out formodel_validator
, which we set tomode="before"
as our code expected the supplied argument to be a dict. We have the validators defined in order of execution, as stated in v1. However, after the migration, the validators actually run in reverse order, with the last one defined being executed first. The execution order can be remedied by usingmodel_validator(mode="after")
but that would require some refactoring to use the model instance instead. The issue can also be remedied by reversing the order the validators are defined in, eg. definingfirst_validator
last.My main question, is this intended behavior?
In pydantic v1, using
root_validator(pre=True)
DOES execute the validators in order of their definition and that fact is stated in the docs. It seems interesting that the execution order would be totally reversed in v2 without explicitly stating that somewhere in the changelog or migration guide.Here's a little test script that demonstrates what I described (there's one for each version, v1 and v2, so you only have to worry about running it against the right version):
Run this with
pydantic 1.10.12
v1:Run this with
pydantic 2.0.3
v2:Beta Was this translation helpful? Give feedback.
All reactions