Pydantic
Data validation and settings management using Python type annotations.
Usage
One good usage of Pydantic is settings validation. It can load secrets from env, files, and customize the priority of sources.
Models
- File Parsing:
parse_obj(similar to__init__but takes adict),parse_raw,prase_file - Models can be created at runtime dynamically
- Custom
__root__type can be specified, so that argument ofparse_objwill be validated against the root type. Similarly, custom__iter__,__getitem__can be implemented, to allow Pydantic models support a type other than mapping. Configallow_mutablecan be turned ofform_modecan be enabled to makeparse_objsupport models beyond dict.underscore_attrs_are_privatecan be set
- Field orders are preserved — only guaranteed on annotated fields.
- Declare required fields by only annotation or
...as the value.a: int | Noneis optional,a: int | None = ...can beNonebut is required. Field(default_factory=...)to set dynamic defaults.ClassVarandPrivateVarcan be used.- Structural pattern matching is supported:
case Pet(species='dog', name=dog_name)
Field Types
- Use
@validator('infinite')to validate the first value in a generator without actually consuming the value. - With
Union, Pydantic attempts to use the first matched type, this can lead to unexpected behaviors. (e.g.UUIDtreated as anint). Thus the first type in union should be the most specific. pet: Cat | Dog = Field(..., discriminator='pet_type), the discriminator must be a field under types that are discriminated among.@validate_argument- Can be used to validate the arguments of a function.
Fieldcan be used in function signature to provide validation.func.validate(arg1, arg2)can be used to validate args without calling.func.raw_functioncan be used to directly call the function
- Use
TypeAdapterto create ad-hoc validators for non-BaseModeltypes.