-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Initial Checks
- I confirm that I'm using Pydantic V2
Description
Got a bit confused about validation of defaults which I knew I'd seen, firstly I expected it to be in the section on model config (maybe an opportunity to put a link in there to the validators section?)
When I looked around some more I was led to Validation of default values¶:
Validators won't run when the default value is used. This applies both to
@field_validatorvalidators andAnnotatedvalidators. You can force them to run withField(validate_defaults=True). Settingvalidate_defaultto True has the closest behavior to usingalways=Truein validator in Pydantic v1. However, you are generally better off using a@model_validator(mode='before')where the function is called before the inner validator is called.
I ran the code section as written
Field(validate_defaults=True)...
after scratching my head for a second I realised there's a typo, in the 2nd usage it changes to the correct form:
Setting
validate_defaultto True...
Looks like a single instance
pydantic/docs/usage/validators.md
Line 269 in d110b47
| You can force them to run with `Field(validate_defaults=True)`. Setting `validate_default` to `True` has the closest behavior to using `always=True` in `validator` in Pydantic v1. However, you are generally better off using a `@model_validator(mode='before')` where the function is called before the inner validator is called. |
Example Code
No response
Python, Pydantic & OS Version
pydantic version: 2.1.1
pydantic-core version: 2.4.0
pydantic-core build: profile=release pgo=true mimalloc=true
install path: /home/louis/miniconda3/lib/python3.10/site-packages/pydantic
python version: 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0]
platform: Linux-5.15.0-76-generic-x86_64-with-glibc2.31
optional deps. installed: ['typing-extensions']
Selected Assignee: @hramezani