https://github.com/planet-a-ventures/pydantic-flatten-rootmodel
Library to flatten a Pydantic (www.github.com/pydantic/pydantic) RootModel into a flattened BaseModel
https://github.com/planet-a-ventures/pydantic-flatten-rootmodel
flatten pydantic python rootmodel
Last synced: about 1 year ago
JSON representation
Library to flatten a Pydantic (www.github.com/pydantic/pydantic) RootModel into a flattened BaseModel
- Host: GitHub
- URL: https://github.com/planet-a-ventures/pydantic-flatten-rootmodel
- Owner: planet-a-ventures
- License: mit
- Created: 2024-12-20T16:12:32.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-01-31T10:47:12.000Z (over 1 year ago)
- Last Synced: 2025-02-14T09:41:19.487Z (over 1 year ago)
- Topics: flatten, pydantic, python, rootmodel
- Language: Python
- Homepage:
- Size: 54.7 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# pydantic-flatten-rootmodel
[](https://pypi.org/project/pydantic-flatten-rootmodel/)
Library to transform a [Pydantic](https://pydantic.dev/)
[RootModel](https://docs.pydantic.dev/latest/api/root_model/)
with discriminated unions into a flattened BaseModel.
```py
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:
```py
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](https://dlthub.com) for it's
[schema definition](https://dlthub.com/docs/general-usage/resource#define-a-schema-with-pydantic).
Without flattening it, the discriminated union is not recognized correctly
when setting up the table schema.