Wrap Python type hints for customized `Annotated` types with `Union`

339 Views Asked by At

Okay, so the idea is that in Pydantic, one can do something like this:

from typing import Literal
from pydantic import BaseModel, Field


class A(BaseModel):
    disc: Literal["a"]
    other: str = "asdf"

class B(BaseModel):
    disc: Literal["b"]
    other: int = 23


class Thing(BaseModel):
    foo: Annotated[Union[A, B], Field(discriminator="disc")]

And I am creating a base model that will always contain the same discriminator.

Basically I'd like to subclass Thing and not worry about the

Annotated[..., Field(discriminator="disc")]

part at all.

Basically, I wanted something like:

CustomUnion[A,B,...]

that would be equivalent to:

Annotated[Union[A, B,...], Field(discriminator="disc")]

I think I can go as far as this:

from typing import TypeVar, Union
from pydantic import BaseModel


BaseModelT = TypeVar("BaseModelT", bound=BaseModel)
Disc = Annotated[BaseModelT, Field(discriminator="disc")]

Disc[Union[A, B, ...]]

But I'd like to go flatter, enforcing also at least two parameters like Union does.

0

There are 0 best solutions below