The validation evolution: Pydantic V2tronger - Marcelo Trylesinski¶
(One of my summaries of the 2023 Dutch pythonconferentie python meeting in Utrecht, NL).
Pydantic is a data validation library. It uses/extends python type hints to work during runtime instead of statically.
Pydantic recently went from version 1 to 2. One of the changes was to split pydantic in a few packages. Pydantic core is now partially written in Rust! Some other changes:
In Version 1 you could add a
Configclass inside your model class, but it was sensitive to spelling mistakes. Now they use amodel_configattribute that prevents errors.As they were breaking the API anyway, they took the opportunity to change lots of names to make them clearer.
@validatoris now@field_validatorwhich accepts extra attributes, for instance for doing a special check before or after the regular validation. “After” validations are handy as you can run a check after pydaantic has ensured it was the correct type, this prevents lots of error handling in your custom validation.BaseSettingsis now in a separate python package as it got a bit too big.Several
__something__methods were changed to give you more options to change pydantic’s behaviour.
Some performance tips (see also https://docs.pydantic.dev/latest/concepts/performance/ ):
Use
model_validate_json()on a json string instead ofmodel_validate(json.loads(...)), as the string gets send to Rust directly, which is quicker.TypeAdaptercan help you speed up your code if you instantiate a similar type multiple times.Use
Literal, notEnum.Use
TypedDictinstead of nested models.
If there is a version 3, it won’t be as big as a change as from 1 to 2.