Dataclasses + Defaults#

The default= argument can be used to override default values in dataclass types.

Warning

We advise against mutation of configuration objects from a dataclass’s __post_init__ method [1]. In the example below, __post_init__ would be called twice: once for the Args() object provided as a default value and another time for the Args() objected instantiated by tyro.cli(). This can cause confusing behavior! Instead, we show below one example of how derived fields can be defined immutably.

 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    @property
18    def derived_field(self) -> str:
19        return ", ".join([self.field1] * self.field2)
20
21
22if __name__ == "__main__":
23    args = tyro.cli(
24        Args,
25        default=Args(
26            field1="default string",
27            field2=tyro.MISSING,
28        ),
29    )
30    print(args.derived_field)

python 01_basics/03_dataclasses_defaults.py --help
usage: 03_dataclasses_defaults.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. (default: 'default string')       │
│ --field2 INT        A numeric field, with a default value. (required) │
╰───────────────────────────────────────────────────────────────────────╯

python 01_basics/03_dataclasses_defaults.py --field2 3
default string, default string, default string

python 01_basics/03_dataclasses_defaults.py --field1 hello --field2 5
hello, hello, hello, hello, hello