Choices#

typing.Literal[] can be used to restrict inputs to a fixed set of literal choices.

 1import dataclasses
 2import enum
 3from typing import Literal
 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    # We can use Literal[] to restrict the set of allowable inputs, for example, over
17    # a set of strings.
18    strings: Literal["red", "green"] = "red"
19
20    # Enums also work.
21    enums: Literal[Color.RED, Color.GREEN] = Color.RED
22
23    # Or mix them with other types!
24    mixed: Literal[Color.RED, Color.GREEN, "blue"] = "blue"
25
26
27if __name__ == "__main__":
28    args = tyro.cli(Args)
29    print(args)

python 01_basics/06_literals.py --help
usage: 06_literals.py [-h] [--strings {red,green}] [--enums {RED,GREEN}]
                      [--mixed {RED,GREEN,blue}]

╭─ options ──────────────────────────────────────────────────────────────────╮
│ -h, --help              show this help message and exit                    │
│ --strings {red,green}   We can use Literal[] to restrict the set of        │
│                         allowable inputs, for example, over a set of       │
│                         strings. (default: red)                            │
│ --enums {RED,GREEN}     Enums also work. (default: RED)                    │
│ --mixed {RED,GREEN,blue}                                                   │
│                         Or mix them with other types! (default: blue)      │
╰────────────────────────────────────────────────────────────────────────────╯