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.

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-1.0.0.tar.gz (4.0 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-1.0.0-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pydantic_autotag-1.0.0.tar.gz
Algorithm Hash digest
SHA256 363c58def81624b3ff67ad8f1ed1b831ec6e74f136713be852fac8de5a71b7a7
MD5 dc758b91f975d2d65f8ad5e21cd7bfba
BLAKE2b-256 af801e1687bd5afe8460d4aeb496399b0c0b8e458bcfdecb6729fe5f05cbb9d7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pydantic_autotag-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7732b4dc6e85327d1d8efecc8edccfff99134a8cfcc69ec3879665793e5d1ece
MD5 f7abc00907a0d55631ba0f6139c2910b
BLAKE2b-256 0a49a6b97daa5232fa0b2bacf878d2c0c0aced58f16c5a7e3caf4ea03c5ad32c

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