Pydantic

Homepage and docs

The BaseModel methods and properties

  1. constr: Defines a string with constraints, such as minimum and maximum length, regex pattern matching, etc.
  2. conint: Represents an integer with constraints, like a range specified by minimum (ge, gt) and maximum (le, lt) values.
  3. confloat: A floating-point number with constraints, including minimum, maximum, and whether to allow infinity or NaN values.
  4. conlist: A list with constraints on its elements' type and the list's minimum and maximum length.
  5. condict: A dictionary with constraints on key and value types, as well as minimum and maximum size.
  6. condecimal: A decimal type with constraints such as fixed places and maximum digits.
  7. EmailStr: A string representing an email address, validated against a standard email regex pattern.
  8. UrlStr: A string formatted as a URL, validated via regex to ensure it's a well-formed URL.
  9. Json: A string that must be valid JSON; Pydantic will parse and serialize the JSON automatically.
  10. SecretStr and SecretBytes: For storing secrets like passwords and tokens. The secret values are not dumped in logs or error messages, enhancing security.
  11. IPv4Address, IPv6Address, IPvAnyAddress: Represent IPv4, IPv6, or either type of IP address, validated to ensure they are correctly formatted.
  12. UUID1, UUID4, UUID3, UUID5: Represents UUIDs (Universally Unique Identifiers) of various versions, ensuring they are valid UUID strings.
  13. FilePath, DirectoryPath, Path: Types for file and directory paths, ensuring the paths exist and optionally that the path is a file or directory.
  14. PositiveInt, NegativeInt, PositiveFloat, NegativeFloat: Integers or floats constrained to be strictly positive or negative.
  15. StrictStr, StrictBool, StrictInt, StrictFloat: Types that require values to be explicitly of the correct type, without any of the automatic casting Pydantic usually performs.

pip install pydantic

from pydantic import (
    BaseModel,
    constr,
    conint,
    confloat,
    conlist,
    condecimal,
    EmailStr,
    UrlStr,
    Json,
    SecretStr,
    SecretBytes,
    IPv4Address,
    IPv6Address,
    FilePath,
    DirectoryPath,
    Path,
    PositiveInt,
    NegativeInt,
    PositiveFloat,
    NegativeFloat,
    StrictStr,
    StrictBool,
    StrictInt,
    StrictFloat,
)

from pydantic.types import UUID1, UUID3, UUID4, UUID5
from pydantic.networks import IPv4Address, IPv6Address, IPvAnyAddress

The types are somewhat documented here

Network types are documented here


pip install email-validator

Here is how to use annotated validators

Here are various ways to constrain fields including annotated

Field validators are documented here

Model validators are here