Generic Types (Python 3.12+ syntax)#
Example of parsing for generic dataclasses using syntax introduced in Python
3.12. Note: this is not compatible with from __future__ import annotations
.
1import dataclasses
2
3import tyro
4
5
6@dataclasses.dataclass(frozen=True)
7class Point3[ScalarType: (int, float)]:
8 x: ScalarType
9 y: ScalarType
10 z: ScalarType
11 frame_id: str
12
13
14@dataclasses.dataclass(frozen=True)
15class Triangle:
16 a: Point3[float]
17 b: Point3[float]
18 c: Point3[float]
19
20
21@dataclasses.dataclass(frozen=True)
22class Args[ShapeType]:
23 shape: ShapeType
24
25
26if __name__ == "__main__":
27 args = tyro.cli(Args[Triangle])
28 print(args)
python 04_additional/06_generics_py312.py --help
usage: 06_generics_py312.py [-h] [OPTIONS] ╭─ options ───────────────────────────────────────────────╮ │ -h, --help show this help message and exit │ ╰─────────────────────────────────────────────────────────╯ ╭─ shape.a options ───────────────────────────────────────╮ │ --shape.a.x FLOAT (required) │ │ --shape.a.y FLOAT (required) │ │ --shape.a.z FLOAT (required) │ │ --shape.a.frame-id STR (required) │ ╰─────────────────────────────────────────────────────────╯ ╭─ shape.b options ───────────────────────────────────────╮ │ --shape.b.x FLOAT (required) │ │ --shape.b.y FLOAT (required) │ │ --shape.b.z FLOAT (required) │ │ --shape.b.frame-id STR (required) │ ╰─────────────────────────────────────────────────────────╯ ╭─ shape.c options ───────────────────────────────────────╮ │ --shape.c.x FLOAT (required) │ │ --shape.c.y FLOAT (required) │ │ --shape.c.z FLOAT (required) │ │ --shape.c.frame-id STR (required) │ ╰─────────────────────────────────────────────────────────╯