Dataclasses#
Common pattern: use tyro.cli()
to instantiate a dataclass. The outputted instance
can be used as a typed alternative for an argparse namespace.
1import dataclasses
2
3import tyro
4
5
6@dataclasses.dataclass
7class Args:
8 """Description.
9 This should show up in the helptext!"""
10
11 field1: str
12 """A string field."""
13
14 field2: int = 3
15 """A numeric field, with a default value."""
16
17
18if __name__ == "__main__":
19 args = tyro.cli(Args)
20 print(args)
python 01_basics/02_dataclasses.py --help
usage: 02_dataclasses.py [-h] --field1 STR [--field2 INT] Description. This should show up in the helptext! ╭─ options ───────────────────────────────────────────────────────────────╮ │ -h, --help show this help message and exit │ │ --field1 STR A string field. (required) │ │ --field2 INT A numeric field, with a default value. (default: 3) │ ╰─────────────────────────────────────────────────────────────────────────╯
python 01_basics/02_dataclasses.py --field1 hello
Args(field1='hello', field2=3)
python 01_basics/02_dataclasses.py --field1 hello --field2 5
Args(field1='hello', field2=5)