.. Comment: this file is automatically generated by `update_example_docs.py`.
   It should not be modified manually.

.. _example-category-basics:

Basics
======

In these examples, we show basic examples of using :func:`tyro.cli`: functions,
dataclasses, supported annotations, and configuration.


.. _example-01_functions:

Functions
---------

In the simplest case, :func:`tyro.cli()` can be used to run a function with
arguments populated from the CLI.


.. code-block:: python
    :linenos:

    # 01_functions.py
    import tyro

    def main(field1: str, field2: int = 3) -> None:
        """Function, whose arguments will be populated from a CLI interface.

        Args:
            field1: A string field.
            field2: A numeric field, with a default value.
        """
        print(field1, field2)

    if __name__ == "__main__":
        tyro.cli(main)


We can use ``--help`` to show the help message, or ``--field1`` and
``--field2`` to set the arguments:

.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./01_functions.py --help</strong>
    <span style="font-weight: bold">usage</span>: 01_functions.py [-h] --field1 <span style="font-weight: bold">STR</span> [--field2 <span style="font-weight: bold">INT</span>]
    
    Function, whose arguments will be populated from a CLI interface.
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">──────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help          <span style="font-weight: lighter">show this help message and exit</span>                     <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field1 <span style="font-weight: bold">STR</span>        <span style="font-weight: lighter">A string field.</span> <span style="font-weight: bold; color: #e60000">(required)</span>                          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field2 <span style="font-weight: bold">INT</span>        <span style="font-weight: lighter">A numeric field, with a default value.</span> <span style="color: #008080">(default: 3)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰─────────────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./01_functions.py --field1 hello</strong>
    hello 3
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./01_functions.py --field1 hello --field2 10</strong>
    hello 10
    </pre>
.. _example-02_dataclasses:

Dataclasses
-----------

In addition to functions, :func:`tyro.cli()` can also take dataclasses as input.


.. code-block:: python
    :linenos:

    # 02_dataclasses.py
    from dataclasses import dataclass
    from pprint import pprint

    import tyro

    @dataclass
    class Args:
        """Description.
        This should show up in the helptext!"""

        field1: str
        """A string field."""

        field2: int = 3
        """A numeric field, with a default value."""

    if __name__ == "__main__":
        args = tyro.cli(Args)
        pprint(args)


To show the help message, we can use the ``--help`` flag:

.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./02_dataclasses.py --help</strong>
    <span style="font-weight: bold">usage</span>: 02_dataclasses.py [-h] --field1 <span style="font-weight: bold">STR</span> [--field2 <span style="font-weight: bold">INT</span>]
    
    Description. This should show up in the helptext!
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">──────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help          <span style="font-weight: lighter">show this help message and exit</span>                     <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field1 <span style="font-weight: bold">STR</span>        <span style="font-weight: lighter">A string field.</span> <span style="font-weight: bold; color: #e60000">(required)</span>                          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field2 <span style="font-weight: bold">INT</span>        <span style="font-weight: lighter">A numeric field, with a default value.</span> <span style="color: #008080">(default: 3)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰─────────────────────────────────────────────────────────────────────────╯</span>
    </pre>

We can override ``field1`` and ``field2``:

.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./02_dataclasses.py --field1 hello</strong>
    Args(field1='hello', field2=3)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./02_dataclasses.py --field1 hello --field2 5</strong>
    Args(field1='hello', field2=5)
    </pre>
.. _example-03_multivalue:

Multi-value Arguments
---------------------

Arguments of both fixed and variable lengths can be annotated with standard
Python collection types. For Python 3.7 and 3.8, we can use either ``from
__future__ import annotations`` to support ``list[T]`` and ``tuple[T]``,
or the older :py:class:`typing.List` and :py:data:`typing.Tuple`.


.. code-block:: python
    :linenos:

    # 03_multivalue.py
    import pathlib
    from dataclasses import dataclass
    from pprint import pprint

    import tyro

    @dataclass
    class Config:
        # Example of a variable-length tuple. `list[T]`, `set[T]`,
        # `dict[K, V]`, etc are supported as well.
        source_paths: tuple[pathlib.Path, ...]
        """This can be multiple!"""

        # Fixed-length tuples are also okay.
        dimensions: tuple[int, int] = (32, 32)
        """Height and width."""

    if __name__ == "__main__":
        config = tyro.cli(Config)
        pprint(config)


To print help:

.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./03_multivalue.py --help</strong>
    <span style="font-weight: bold">usage</span>: 03_multivalue.py [-h] --source-paths <span style="font-weight: bold">[PATH</span>
    <span style="font-weight: bold">                        [PATH ...]]</span> [--dimensions <span style="font-weight: bold">INT INT</span>]
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">─────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help              <span style="font-weight: lighter">show this help message and exit</span>    <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --source-paths <span style="font-weight: bold">[PATH [PATH ...]]</span>                           <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="font-weight: lighter">This can be multiple!</span> <span style="font-weight: bold; color: #e60000">(required)</span>   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --dimensions <span style="font-weight: bold">INT INT</span>    <span style="font-weight: lighter">Height and width.</span> <span style="color: #008080">(default: 32 32)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────╯</span>
    </pre>

We can override arguments:

.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./03_multivalue.py --source-paths ./data --dimensions 16 16</strong>
    Config(source_paths=(PosixPath('data'),), dimensions=(16, 16))
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./03_multivalue.py --source-paths ./data1 ./data2</strong>
    Config(source_paths=(PosixPath('data1'), PosixPath('data2')),
           dimensions=(32, 32))
    </pre>
.. _example-04_flags:

Booleans and Flags
------------------

Booleans can either be expected to be explicitly passed in, or, if given a default
value, automatically converted to flags.

To turn off conversion, see :class:`tyro.conf.FlagConversionOff`.


.. code-block:: python
    :linenos:

    # 04_flags.py
    from dataclasses import dataclass
    from pprint import pprint

    import tyro

    @dataclass
    class Args:
        # Boolean. This expects an explicit "True" or "False".
        boolean: bool

        # Optional boolean. Same as above, but can be omitted.
        optional_boolean: bool | None = None

        # Pass --flag-a in to set this value to True.
        flag_a: bool = False

        # Pass --no-flag-b in to set this value to False.
        flag_b: bool = True

    if __name__ == "__main__":
        args = tyro.cli(Args)
        pprint(args)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./04_flags.py --help</strong>
    <span style="font-weight: bold">usage</span>: 04_flags.py [-h] [OPTIONS]
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">───────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help                                                               <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">show this help message and exit</span>                                      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --boolean <span style="font-weight: bold">{True,False}</span>                                                   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Boolean. This expects an explicit "True" or "False".</span> <span style="font-weight: bold; color: #e60000">(required)</span>      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --optional-boolean <span style="font-weight: bold">{None,True,False}</span>                                     <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Optional boolean. Same as above, but can be omitted.</span> <span style="color: #008080">(default: None)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --flag-a, --no-flag-a                                                    <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Pass --flag-a in to set this value to True.</span> <span style="color: #008080">(default: False)</span>         <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --flag-b, --no-flag-b                                                    <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Pass --no-flag-b in to set this value to False.</span> <span style="color: #008080">(default: True)</span>      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰──────────────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./04_flags.py --boolean True</strong>
    Args(boolean=True, optional_boolean=None, flag_a=False, flag_b=True)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./04_flags.py --boolean False --flag-a</strong>
    Args(boolean=False, optional_boolean=None, flag_a=True, flag_b=True)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./04_flags.py --boolean False --no-flag-b</strong>
    Args(boolean=False, optional_boolean=None, flag_a=False, flag_b=False)
    </pre>
.. _example-05_choices:

Choices
-------

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


.. code-block:: python
    :linenos:

    # 05_choices.py
    import dataclasses
    from pprint import pprint
    from typing import Literal

    import tyro

    @dataclasses.dataclass
    class Args:
        # We can use Literal[] to restrict the set of allowable inputs, for example, over
        # a set of strings.
        string: Literal["red", "green"] = "red"

        # Integers also work. (as well as booleans, enums, etc)
        number: Literal[0, 1, 2] = 0

    if __name__ == "__main__":
        args = tyro.cli(Args)
        pprint(args)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./05_choices.py --help</strong>
    <span style="font-weight: bold">usage</span>: 05_choices.py [-h] [--string <span style="font-weight: bold">{red,green}</span>] [--number <span style="font-weight: bold">{0,1,2}</span>]
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">─────────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help              <span style="font-weight: lighter">show this help message and exit</span>                    <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --string <span style="font-weight: bold">{red,green}</span>    <span style="font-weight: lighter">We can use Literal[] to restrict the set of </span>       <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="font-weight: lighter">allowable inputs, for example, over a set of </span>      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="font-weight: lighter">strings.</span> <span style="color: #008080">(default: red)</span>                            <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --number <span style="font-weight: bold">{0,1,2}</span>        <span style="font-weight: lighter">Integers also work. (as well as booleans, enums, </span>  <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="font-weight: lighter">etc)</span> <span style="color: #008080">(default: 0)</span>                                  <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./05_choices.py --string red</strong>
    Args(string='red', number=0)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./05_choices.py --string blue</strong>
    <span style="color: #e60000">╭─</span><span style="color: #e60000"> </span><span style="font-weight: bold; color: #e60000">Parsing error</span><span style="color: #e60000"> </span><span style="color: #e60000">───────────────────────────────────────────────────────</span><span style="color: #e60000">─╮</span>
    <span style="color: #e60000">│</span> Argument --string: invalid choice: 'blue' (choose from 'red', 'green') <span style="color: #e60000">│</span>
    <span style="color: #e60000">│</span> <span style="color: #800000">──────────────────────────────────────────────────────────────────────</span> <span style="color: #e60000">│</span>
    <span style="color: #e60000">│</span> For full helptext, run <span style="font-weight: bold">05_choices.py --help</span>                            <span style="color: #e60000">│</span>
    <span style="color: #e60000">╰────────────────────────────────────────────────────────────────────────╯</span>
    </pre>
.. _example-06_enums:

Enums
-----

In addition to literals, enums can also be used to provide a fixed set of
choices.


.. code-block:: python
    :linenos:

    # 06_enums.py
    import enum
    from dataclasses import dataclass
    from pprint import pprint

    import tyro

    class Color(enum.Enum):
        RED = enum.auto()
        BLUE = enum.auto()

    @dataclass
    class Config:
        color: Color = Color.RED
        """Color argument."""

        opacity: float = 0.5
        """Opacity argument."""

    if __name__ == "__main__":
        config = tyro.cli(Config)
        pprint(config)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./06_enums.py --help</strong>
    <span style="font-weight: bold">usage</span>: 06_enums.py [-h] [--color <span style="font-weight: bold">{RED,BLUE}</span>] [--opacity <span style="font-weight: bold">FLOAT</span>]
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">───────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help              <span style="font-weight: lighter">show this help message and exit</span>  <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --color <span style="font-weight: bold">{RED,BLUE}</span>      <span style="font-weight: lighter">Color argument.</span> <span style="color: #008080">(default: RED)</span>   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --opacity <span style="font-weight: bold">FLOAT</span>         <span style="font-weight: lighter">Opacity argument.</span> <span style="color: #008080">(default: 0.5)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰──────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./06_enums.py --color RED</strong>
    Config(color=&lt;Color.RED: 1&gt;, opacity=0.5)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./06_enums.py --color BLUE --opacity 0.75</strong>
    Config(color=&lt;Color.BLUE: 2&gt;, opacity=0.75)
    </pre>
.. _example-07_unions:

Unions
------

:code:`X | Y` or :code:`typing.Union[X, Y]` can be used to expand inputs to
multiple types.


.. code-block:: python
    :linenos:

    # 07_unions.py
    import dataclasses
    import enum
    from pprint import pprint
    from typing import Literal, Optional

    import tyro

    class Color(enum.Enum):
        RED = enum.auto()
        GREEN = enum.auto()
        BLUE = enum.auto()

    @dataclasses.dataclass(frozen=True)
    class Args:
        # Unions can be used to specify multiple allowable types.
        union_over_types: int | str = 0
        string_or_enum: Literal["red", "green"] | Color = "red"

        # Unions also work over more complex nested types.
        union_over_tuples: tuple[int, int] | tuple[str] = ("1",)

        # And can be nested in other types.
        tuple_of_string_or_enum: tuple[Literal["red", "green"] | Color, ...] = (
            "red",
            Color.RED,
        )

        # Optional[T] is equivalent to `T | None`.
        integer: Optional[Literal[0, 1, 2, 3]] = None

    if __name__ == "__main__":
        args = tyro.cli(Args)
        pprint(args)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./07_unions.py --help</strong>
    <span style="font-weight: bold">usage</span>: 07_unions.py [-h] [OPTIONS]
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">─────────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help                                                                 <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">show this help message and exit</span>                                        <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --union-over-types <span style="font-weight: bold">INT|STR</span>                                                 <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Unions can be used to specify multiple allowable types.</span> <span style="color: #008080">(default: 0)</span>   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --string-or-enum <span style="font-weight: bold">{red,green,RED,GREEN,BLUE}</span>                                <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Unions can be used to specify multiple allowable types.</span> <span style="color: #008080">(default: red)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --union-over-tuples <span style="font-weight: bold">{INT INT}|STR</span>                                          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Unions also work over more complex nested types.</span> <span style="color: #008080">(default: 1)</span>          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --tuple-of-string-or-enum <span style="font-weight: bold">[{red,green,RED,GREEN,BLUE} </span>                     <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> <span style="font-weight: bold">[{red,green,RED,GREEN,BLUE} ...]]</span>                                          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">And can be nested in other types.</span> <span style="color: #008080">(default: red RED)</span>                   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --integer <span style="font-weight: bold">{None,0,1,2,3}</span>                                                   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>     <span style="font-weight: lighter">Optional[T] is equivalent to `T | None`.</span> <span style="color: #008080">(default: None)</span>               <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./07_unions.py --union-over-types 3</strong>
    Args(union_over_types=3,
         string_or_enum='red',
         union_over_tuples=('1',),
         tuple_of_string_or_enum=('red', &lt;Color.RED: 1&gt;),
         integer=None)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./07_unions.py --union-over-types three</strong>
    Args(union_over_types='three',
         string_or_enum='red',
         union_over_tuples=('1',),
         tuple_of_string_or_enum=('red', &lt;Color.RED: 1&gt;),
         integer=None)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./07_unions.py --integer None</strong>
    Args(union_over_types=0,
         string_or_enum='red',
         union_over_tuples=('1',),
         tuple_of_string_or_enum=('red', &lt;Color.RED: 1&gt;),
         integer=None)
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./07_unions.py --integer 0</strong>
    Args(union_over_types=0,
         string_or_enum='red',
         union_over_tuples=('1',),
         tuple_of_string_or_enum=('red', &lt;Color.RED: 1&gt;),
         integer=0)
    </pre>
.. _example-08_positional:

Positional Arguments
--------------------

Positional-only arguments in functions are converted to positional CLI arguments.

For more general positional arguments, see :class:`tyro.conf.Positional`.


.. code-block:: python
    :linenos:

    # 08_positional.py
    from __future__ import annotations

    import pathlib

    import tyro

    def main(
        source: pathlib.Path,
        dest: pathlib.Path,
        /,  # Mark the end of positional arguments.
        verbose: bool = False,
    ) -> None:
        """Command-line interface defined using a function signature. This
        docstring is parsed to generate helptext.

        Args:
            source: Source path.
            dest: Destination path.
            verbose: Explain what is being done.
        """
        print(f"{source=}\n{dest=}\n{verbose=}")

    if __name__ == "__main__":
        tyro.cli(main)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python 08_positional.py --help</strong>
    <span style="font-weight: bold">usage</span>: 08_positional.py [-h] [--verbose | --no-verbose] <span style="font-weight: bold">PATH</span> <span style="font-weight: bold">PATH</span>
    
    Command-line interface defined using a function signature. This docstring is 
    parsed to generate helptext.
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> positional arguments </span><span style="font-weight: lighter">────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> PATH              <span style="font-weight: lighter">Source path.</span> <span style="font-weight: bold; color: #e60000">(required)</span>                      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> PATH              <span style="font-weight: lighter">Destination path.</span> <span style="font-weight: bold; color: #e60000">(required)</span>                 <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────╯</span>
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">─────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help        <span style="font-weight: lighter">show this help message and exit</span>              <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --verbose, --no-verbose                                        <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                   <span style="font-weight: lighter">Explain what is being done.</span> <span style="color: #008080">(default: False)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python 08_positional.py ./a ./b</strong>
    source=PosixPath('a')
    dest=PosixPath('b')
    verbose=False
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python 08_positional.py ./test1 ./test2 --verbose</strong>
    source=PosixPath('test1')
    dest=PosixPath('test2')
    verbose=True
    </pre>
.. _example-09_conf:

Configuration via typing.Annotated[]
------------------------------------

The :mod:`tyro.conf` module contains utilities that can be used in conjunction
with :py:data:`typing.Annotated` to configure command-line interfaces beyond
what is expressible via static type annotations.

Features here are supported, but generally unnecessary and should be used sparingly.


.. code-block:: python
    :linenos:

    # 09_conf.py
    import dataclasses

    from typing_extensions import Annotated

    import tyro

    @dataclasses.dataclass
    class Args:
        # A numeric field parsed as a positional argument.
        positional: tyro.conf.Positional[int]

        # A boolean field with flag conversion turned off.
        boolean: tyro.conf.FlagConversionOff[bool] = False

        # A numeric field that can't be changed via the CLI.
        fixed: tyro.conf.Fixed[int] = 5

        # A field with manually overridden properties.
        manual: Annotated[
            str,
            tyro.conf.arg(
                name="renamed",
                metavar="STRING",
                help="A field with manually overridden properties!",
            ),
        ] = "Hello"

    if __name__ == "__main__":
        print(tyro.cli(Args))




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./09_conf.py --help</strong>
    <span style="font-weight: bold">usage</span>: 09_conf.py [-h] [OPTIONS] <span style="font-weight: bold">INT</span>
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> positional arguments </span><span style="font-weight: lighter">────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> INT                     <span style="font-weight: lighter">A numeric field parsed as a positional argument.</span>   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="font-weight: bold; color: #e60000">(required)</span>                                         <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────────────────╯</span>
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">─────────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help              <span style="font-weight: lighter">show this help message and exit</span>                    <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --boolean <span style="font-weight: bold">{True,False}</span>  <span style="font-weight: lighter">A boolean field with flag conversion turned off.</span>   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="color: #008080">(default: False)</span>                                   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --fixed <span style="font-weight: bold; color: #800000">{fixed}</span>         <span style="font-weight: lighter">A numeric field that can't be changed via the CLI.</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="color: #008080">(fixed to: 5)</span>                                      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --renamed <span style="font-weight: bold">STRING</span>        <span style="font-weight: lighter">A field with manually overridden properties!</span>       <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                         <span style="color: #008080">(default: Hello)</span>                                   <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./09_conf.py 5 --boolean True</strong>
    Args(positional=5, boolean=True, fixed=5, manual='Hello')
    </pre>
.. _example-10_aliases:

Argument Aliases
----------------

:func:`tyro.conf.arg()` can be used to attach aliases to arguments.


.. code-block:: python
    :linenos:

    # 10_aliases.py
    from typing import Annotated

    import tyro

    def checkout(
        branch: Annotated[str, tyro.conf.arg(aliases=["-b"])],
    ) -> None:
        """Check out a branch."""
        print(f"{branch=}")

    if __name__ == "__main__":
        tyro.cli(checkout)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./10_aliases.py --help</strong>
    <span style="font-weight: bold">usage</span>: 10_aliases.py [-h] --branch <span style="font-weight: bold">STR</span>
    
    Check out a branch.
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">──────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help              <span style="font-weight: lighter">show this help message and exit</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --branch <span style="font-weight: bold">STR</span>, -b <span style="font-weight: bold">STR</span>    <span style="font-weight: bold; color: #e60000">(required)</span>                      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰─────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./10_aliases.py --branch main</strong>
    branch='main'
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./10_aliases.py -b main</strong>
    branch='main'
    </pre>
.. _example-11_type_aliases_py312:

Type Aliases (3.12+)
--------------------

In Python 3.12, the :code:`type` statement is introduced to create type aliases.


.. code-block:: python
    :linenos:

    # 11_type_aliases_py312.py
    import dataclasses

    import tyro

    # Lazily-evaluated type alias.
    type Field1Type = Inner

    @dataclasses.dataclass
    class Inner:
        a: int
        b: str

    @dataclasses.dataclass
    class Args:
        """Description.
        This should show up in the helptext!"""

        field1: Field1Type
        """A field."""

        field2: int = 3
        """A numeric field, with a default value."""

    if __name__ == "__main__":
        args = tyro.cli(Args)
        print(args)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./11_type_aliases_py312.py --help</strong>
    <span style="font-weight: bold">usage</span>: 11_type_aliases_py312.py [-h] [--field2 <span style="font-weight: bold">INT</span>] --field1.a <span style="font-weight: bold">INT</span> --field1.b
                                    <span style="font-weight: bold">STR</span>
    
    Description. This should show up in the helptext!
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">────────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help            <span style="font-weight: lighter">show this help message and exit</span>                     <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field2 <span style="font-weight: bold">INT</span>          <span style="font-weight: lighter">A numeric field, with a default value.</span> <span style="color: #008080">(default: 3)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰───────────────────────────────────────────────────────────────────────────╯</span>
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> field1 options </span><span style="font-weight: lighter">─────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> <span style="font-weight: bold">A field.                                                                 </span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> <span style="font-weight: lighter">────────────────────────────────                                         </span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field1.a <span style="font-weight: bold">INT</span>        <span style="font-weight: bold; color: #e60000">(required)</span>                                          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field1.b <span style="font-weight: bold">STR</span>        <span style="font-weight: bold; color: #e60000">(required)</span>                                          <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰───────────────────────────────────────────────────────────────────────────╯</span>
    </pre>
.. _example-12_counters:

Counters
--------

Repeatable 'counter' arguments can be specified via :data:`tyro.conf.UseCounterAction`.


.. code-block:: python
    :linenos:

    # 12_counters.py
    from typing_extensions import Annotated

    import tyro
    from tyro.conf import UseCounterAction

    def main(
        verbosity: UseCounterAction[int],
        aliased_verbosity: Annotated[UseCounterAction[int], tyro.conf.arg(aliases=["-v"])],
    ) -> None:
        """Example showing how to use counter actions.

        Args:
            verbosity: Verbosity level.
            aliased_verbosity: Same as above, but can also be specified with -v, -vv, -vvv, etc.
        """
        print("Verbosity level:", verbosity)
        print("Verbosity level (aliased):", aliased_verbosity)

    if __name__ == "__main__":
        tyro.cli(main)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./12_counters.py --help</strong>
    <span style="font-weight: bold">usage</span>: 12_counters.py [-h] [--verbosity] [--aliased-verbosity]
    
    Example showing how to use counter actions.
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">─────────────────────────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help         <span style="font-weight: lighter">show this help message and exit</span>                         <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --verbosity        <span style="font-weight: lighter">Verbosity level.</span> <span style="color: #008080">(repeatable)</span>                           <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --aliased-verbosity, -v                                                    <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                    <span style="font-weight: lighter">Same as above, but can also be specified with -v, -vv, </span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span>                    <span style="font-weight: lighter">-vvv, etc.</span> <span style="color: #008080">(repeatable)</span>                                 <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰────────────────────────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./12_counters.py --verbosity</strong>
    Verbosity level: 1
    Verbosity level (aliased): 0
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./12_counters.py --verbosity --verbosity</strong>
    Verbosity level: 2
    Verbosity level (aliased): 0
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./12_counters.py -vvv</strong>
    Verbosity level: 0
    Verbosity level (aliased): 3
    </pre>
.. _example-13_classes:

Instantiating Classes
---------------------

In addition to functions and dataclasses, we can also generate CLIs from the
constructors of standard Python classes.


.. code-block:: python
    :linenos:

    # 13_classes.py
    import tyro

    class Args:
        def __init__(
            self,
            field1: str,
            field2: int,
            flag: bool = False,
        ):
            """Arguments.

            Args:
                field1: A string field.
                field2: A numeric field.
                flag: A boolean flag.
            """
            self.data = [field1, field2, flag]

    if __name__ == "__main__":
        args = tyro.cli(Args)
        print(args.data)




.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./13_classes.py --help</strong>
    <span style="font-weight: bold">usage</span>: 13_classes.py [-h] --field1 <span style="font-weight: bold">STR</span> --field2 <span style="font-weight: bold">INT</span> [--flag | --no-flag]
    
    Arguments.
    
    <span style="font-weight: lighter">╭─</span><span style="font-weight: lighter"> options </span><span style="font-weight: lighter">───────────────────────────────────────────────</span><span style="font-weight: lighter">─╮</span>
    <span style="font-weight: lighter">│</span> -h, --help              <span style="font-weight: lighter">show this help message and exit</span>  <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field1 <span style="font-weight: bold">STR</span>            <span style="font-weight: lighter">A string field.</span> <span style="font-weight: bold; color: #e60000">(required)</span>       <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --field2 <span style="font-weight: bold">INT</span>            <span style="font-weight: lighter">A numeric field.</span> <span style="font-weight: bold; color: #e60000">(required)</span>      <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">│</span> --flag, --no-flag       <span style="font-weight: lighter">A boolean flag.</span> <span style="color: #008080">(default: False)</span> <span style="font-weight: lighter">│</span>
    <span style="font-weight: lighter">╰──────────────────────────────────────────────────────────╯</span>
    </pre>



.. raw:: html

    <pre class="highlight" style="padding: 1em; box-sizing: border-box; font-size: 0.85em; line-height: 1.2em;">
    <strong style="opacity: 0.7; padding-bottom: 0.5em; display: inline-block"><span style="user-select: none">$ </span>python ./13_classes.py --field1 hello --field2 7</strong>
    ['hello', 7, False]
    </pre>