Skip to content

Discriminative Union #351

Description

@julien-blanchon

I'm using a lot the following discriminative union pattern:

from typing import Annotated, Literal
from pydantic import Field
from simple_parsing import ArgumentParser

@dataclass
class DatasetImage:
    type: Literal["image"]
    path: str
    resolution: tuple[int, int]


@dataclass
class DatasetVideo:
    type: Literal["video"]
    path: str
    resolution: tuple[int, int]
    fps: int


@dataclass
class Config:
    dataset: Annotated[DatasetImage | DatasetVideo, Field(discriminator="type")]


parser = ArgumentParser()

if __name__ == "__main__":
    parser.add_arguments(Config, "example")
    args = parser.parse_args()
    print(args)

It's working with cyclopts (but still need pydantic for the discriminator field).

With simple-parsing I get this

❯ python main.py --help 
usage: main.py [-h] --dataset Annotated

options:
  -h, --help           show this help message and exit

Config ['example']:
  Config(dataset: Annotated[__main__.DatasetImage | __main__.DatasetVideo, FieldInfo(annotation=NoneType, required=True, discriminator='type')])

  --dataset Annotated

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions