Pydantic

Data validation and settings management using Python type annotations.

Pydantic Documentation

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 a dict), parse_raw, prase_file
  • Models can be created at runtime dynamically
  • Custom __root__ type can be specified, so that argument of parse_obj will be validated against the root type. Similarly, custom __iter__, __getitem__ can be implemented, to allow Pydantic models support a type other than mapping.
  • Config
    • allow_mutable can be turned off
    • orm_mode can be enabled to make parse_obj support models beyond dict.
    • underscore_attrs_are_private can be set
  • Field orders are preserved — only guaranteed on annotated fields.
  • Declare required fields by only annotation or ... as the value. a: int | None is optional, a: int | None = ... can be None but is required.
  • Field(default_factory=...) to set dynamic defaults.
  • ClassVar and PrivateVar can 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. UUID treated as an int). 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.
    • Field can be used in function signature to provide validation.
    • func.validate(arg1, arg2) can be used to validate args without calling.
    • func.raw_function can be used to directly call the function
  • Use TypeAdapter to create ad-hoc validators for non-BaseModel types.