Overview

Pydantic 1.9, released on December 31, 2021, adds discriminated unions for more efficient validation of polymorphic models.

Main Features

Discriminated unions

Discriminated unions use a discriminator field to identify the concrete type, avoiding testing each variant and improving validation performance.

python
from typing import Literal, Union
from pydantic import BaseModel, Field

class Cat(BaseModel):
    type: Literal['cat'] = 'cat'
    meows: bool = True

class Dog(BaseModel):
    type: Literal['dog'] = 'dog'
    barks: bool = True

class Home(BaseModel):
    pet: Union[Cat, Dog] = Field(discriminator='type')

# Fast validation via discriminator
h1 = Home(pet={'type': 'cat', 'meows': True})
h2 = Home(pet={'type': 'dog', 'barks': False})
print(h1.pet)  # type='cat' meows=True
print(h2.pet)  # type='dog' barks=False

Validation improvements

Validation is overall faster with better generic type support and chained custom validators.

python
from pydantic import BaseModel, validator

class User(BaseModel):
    name: str
    email: str
    age: int

    @validator('email')
    def valid_email(cls, v):
        if '@' not in v:
            raise ValueError('Invalid email')
        return v.lower()

    @validator('age')
    def positive_age(cls, v):
        if v < 0:
            raise ValueError('Age must be positive')
        return v

u = User(name='Alice', email='Alice@Example.COM', age=30)
print(u.email)  # alice@example.com

Sources