Skip to content

planet-a-ventures/pydantic-flatten-rootmodel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ba7546e · Jan 31, 2025

History

23 Commits
Jan 8, 2025
Dec 20, 2024
Jan 13, 2025
Dec 20, 2024
Dec 20, 2024
Dec 20, 2024
Jan 13, 2025
Dec 20, 2024
Dec 20, 2024
Dec 20, 2024
Jan 31, 2025
Dec 20, 2024
Jan 8, 2025
Dec 20, 2024
Jan 8, 2025
Jan 8, 2025
Dec 20, 2024

Repository files navigation

pydantic-flatten-rootmodel

PyPI version

Library to transform a Pydantic RootModel with discriminated unions into a flattened BaseModel.

from pydantic_flatten_rootmodel import flatten_root_model

class Cat(BaseModel):
    pet_type: Annotated[Literal["cat"], Field()]
    meow: str


class Dog(BaseModel):
    pet_type: Annotated[Literal["dog"], Field()]
    bark: str

class Pet(RootModel[Cat | Dog]):
    root: Annotated[Cat | Dog, Field(discriminator="pet_type")]


FlattenedPet = flatten_root_model(Pet)

would result in FlattenedPet to have this shape:

class FlattenedPet(BaseModel):
   pet_type: Annotated[Union[Literal["cat"], Literal["dog"]]]
   bark: Union[str, None]
   meow: Union[str, None]

This can for example be leveraged by dlt for it's schema definition. Without flattening it, the discriminated union is not recognized correctly when setting up the table schema.