Unions#
X | Y
or typing.Union[X, Y]
can be used to expand inputs to multiple types.
1import dataclasses
2import enum
3from typing import Literal, Optional
4
5import tyro
6
7
8class Color(enum.Enum):
9 RED = enum.auto()
10 GREEN = enum.auto()
11 BLUE = enum.auto()
12
13
14@dataclasses.dataclass(frozen=True)
15class Args:
16 # Unions can be used to specify multiple allowable types.
17 union_over_types: int | str = 0
18 string_or_enum: Literal["red", "green"] | Color = "red"
19
20 # Unions also work over more complex nested types.
21 union_over_tuples: tuple[int, int] | tuple[str] = ("1",)
22
23 # And can be nested in other types.
24 tuple_of_string_or_enum: tuple[Literal["red", "green"] | Color, ...] = (
25 "red",
26 Color.RED,
27 )
28
29 # Optional[T] is equivalent to `T | None`.
30 integer: Optional[Literal[0, 1, 2, 3]] = None
31
32
33if __name__ == "__main__":
34 args = tyro.cli(Args)
35 print(args)
python 01_basics/07_unions.py --help
usage: 07_unions.py [-h] [OPTIONS] ╭─ options ──────────────────────────────────────────────────────────────────╮ │ -h, --help │ │ show this help message and exit │ │ --union-over-types INT|STR │ │ Unions can be used to specify multiple allowable types. (default: 0) │ │ --string-or-enum {red,green,RED,GREEN,BLUE} │ │ Unions can be used to specify multiple allowable types. (default: red) │ │ --union-over-tuples {INT INT}|STR │ │ Unions also work over more complex nested types. (default: 1) │ │ --tuple-of-string-or-enum [{red,green,RED,GREEN,BLUE} │ │ [{red,green,RED,GREEN,BLUE} ...]] │ │ And can be nested in other types. (default: red RED) │ │ --integer {None,0,1,2,3} │ │ Optional[T] is equivalent to `T | None`. (default: None) │ ╰────────────────────────────────────────────────────────────────────────────╯