Skip to main content

Create Pydantic tagged unions without the boilerplate

Project description

pydantic-autotag

A lightweight Python library that simplifies working with tagged unions in Pydantic by automatically adding discriminator fields to your models and annotating union types. Using discriminators makes deserializing union types dramatically faster since it only has to deserialize the value as the correct type without trying all the other possible types. It also prevents any issues arising if one value

Installation

Install from PyPI:

uv add pydantic-autotag

or

pip install pydantic-autotag

Features

  • Automatic tagging: Add discriminator fields to Pydantic models with a simple decorator
  • Tagged unions: Convert regular unions to Pydantic tagged unions with a single function call
  • Custom field names: Use any field name for discrimination (defaults to "type")
  • Custom tags: Use any function to generate the tag value for each class

Usage

from typing import TypeAlias, TYPE_CHECKING
from pydantic import BaseModel
from pydantic_autotag import autotagged_union

class Foo(BaseModel):
    ...

class Bar(BaseModel):
    ...

# Calling functions is not allowed in type definitions so this won't be accepted:
# FooOrBar = autotagged_union(Foo | Bar)
# Instead, define the union and then apply autotagging only when not type checking.
FooOrBar: TypeAlias = Foo | Bar

if not TYPE_CHECKING:
    FooOrBar = autotagged_union(FooOrBar)

You can also decorate model classes directly:

from pydantic import BaseModel
from pydantic_autotag import autotag

@autotag
class Foo(BaseModel):
    ...

Customization

By default, each class has a type field added to it and the field's value is the class name. This can be customized by passing field_name and/or tag_value keyword arguments to autotagged_union or autotag:

@autotag(field_name="name", tag_value="Happy")
class PositiveEmotion(BaseModel):
    ...

is equivalent to:

class PositiveEmotion(BaseModel):
    name: Literal["Happy"] = Field(init=False, default="Happy", repr=False, frozen=True)
    ...

For unions, you must pass a function that returns the tag value for a given class:

FooOrBar = autotagged_union(FooOrBar, field_name="which", tag_value=lambda c: c.__name__.lower())

Type Safety

If you need to directly access the generated field and don't want your type checker to be unhappy, you can declare the field either as a str or as a Literal["ExpectedTagValue"] and autotag will replace it at runtime just like it would if the field didn't exist. One easy way to do this is with a base class:

class MyBase(BaseModel):
    type: str

class A(MyBase):
    ...

class B(MyBase):
    ...


AorB: TypeAlias = A | B

if not TYPE_CHECKING:
    AorB = autotagged_union(AorB)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_autotag-0.1.0.tar.gz (4.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_autotag-0.1.0-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_autotag-0.1.0.tar.gz.

File metadata

  • Download URL: pydantic_autotag-0.1.0.tar.gz
  • Upload date:
  • Size: 4.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.7.18

File hashes

Hashes for pydantic_autotag-0.1.0.tar.gz
Algorithm Hash digest
SHA256 3cfa1ba55f3f96ddbb67559335a2543a2fd7ff1750bf699a8abebc35d6e7aca1
MD5 f24c08f8a9219c5f58f442c0b0a67725
BLAKE2b-256 d63ed9c2f5d98d1b43d86cc7f7e91c3ffb09e98747e2f1f23f98f131ed0e7f26

See more details on using hashes here.

File details

Details for the file pydantic_autotag-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_autotag-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8607af7714f52ad91556c22e71c4aba4fa3f3997005d6909c7ca7f290ef4a5be
MD5 eb79e001a6b6590fa639ca10bf673bbf
BLAKE2b-256 3e05c4b6bdeaacdae42791f0c8c9b4b0c490847f1d421b829351e0c2c18c7296

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page