tyro.extras

The tyro.extras submodule contains helpers that complement tyro.cli().

Warning

Compared to the core interface, APIs here are more likely to be changed or deprecated.

Package Contents

tyro.extras.set_accent_color(accent_color: str | None) None[source]

Set an accent color to use in help messages. Takes any color supported by rich, see python -m rich.color. Experimental.

Parameters:

accent_color (Optional[str])

Return type:

None

tyro.extras.get_parser(f: tyro._typing.TypeForm[OutT], *, prog: None | str = None, description: None | str = None, default: None | OutT = None, use_underscores: bool = False, console_outputs: bool = True, config: None | Sequence[tyro.conf._markers.Marker] = None, registry: None | tyro.constructors.ConstructorRegistry = None) tyro._argparse.ArgumentParser[source]
tyro.extras.get_parser(f: Callable[Ellipsis, OutT], *, prog: None | str = None, description: None | str = None, default: None | OutT = None, use_underscores: bool = False, console_outputs: bool = True, config: None | Sequence[tyro.conf._markers.Marker] = None, registry: None | tyro.constructors.ConstructorRegistry = None) tyro._argparse.ArgumentParser

Get the argparse.ArgumentParser object generated under-the-hood by tyro.cli(). Useful for tools like sphinx-argparse, argcomplete, etc.

For tab completion, we recommend using tyro.cli()’s built-in --tyro-write-completion flag.

Parameters:
  • f – The function or type to populate from command-line arguments.

  • prog – The name of the program to display in the help text.

  • description – The description text shown at the top of the help output.

  • default – An instance to use for default values.

  • use_underscores – If True, uses underscores as word delimiters in the help text.

  • console_outputs – If set to False, suppresses parsing errors and help messages.

  • config – A sequence of configuration marker objects from tyro.conf.

  • registry – A tyro.constructors.ConstructorRegistry instance containing custom constructor rules.

tyro.extras.overridable_config_cli(configs: Mapping[str, Tuple[str, T]], *, prog: str | None = None, description: str | None = None, args: Sequence[str] | None = None, use_underscores: bool = False, console_outputs: bool = True, config: Sequence[Any] | None = None, sort_subcommands: bool = False, registry: tyro.constructors.ConstructorRegistry | None = None) T[source]

Helper function for creating a CLI interface that allows us to choose between default config objects (typically dataclasses) and override values within it. Turns off subcommand creation for any union types within the config object.

This is a lightweight wrapper over tyro.cli(), with some default arguments populated. Also see tyro.extras.subcommand_type_from_defaults().

Example usage:

import dataclasses

import tyro


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


default_configs = {
    "small": (
        "Small config",
        Config(1, "small"),
    ),
    "big": (
        "Big config",
        Config(100, "big"),
    ),
}
config = tyro.extras.overridable_config_cli(default_configs)
print(config)
Parameters:
  • configs (Mapping[str, Tuple[str, T]]) – A dictionary of config names mapped to a tuple of (description, config object).

  • prog (str | None) – The name of the program printed in helptext. Mirrors argument from argparse.ArgumentParser().

  • description (str | None) – Description text for the parser, displayed when the –help flag is passed in. If not specified, the class docstring is used. Mirrors argument from argparse.ArgumentParser().

  • args (Sequence[str] | None) – If set, parse arguments from a sequence of strings instead of the commandline. Mirrors argument from argparse.ArgumentParser.parse_args().

  • use_underscores (bool) – If True, use underscores as a word delimiter instead of hyphens. This primarily impacts helptext; underscores and hyphens are treated equivalently when parsing happens. We default helptext to hyphens to follow the GNU style guide. https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html

  • console_outputs (bool) – If set to False, parsing errors and help messages will be suppressed.

  • config (Sequence[Any] | None) – Sequence of config marker objects, from tyro.conf. We include tyro.conf.AvoidSubcommands by default.

  • sort_subcommands (bool) – If True, sort the subcommands alphabetically by name.

  • registry (tyro.constructors.ConstructorRegistry | None) – A tyro.constructors.ConstructorRegistry instance containing custom constructor rules.

Return type:

T

tyro.extras.subcommand_type_from_defaults(defaults: Mapping[str, T], descriptions: Mapping[str, str] = {}, *, prefix_names: bool = True, sort_subcommands: bool = False) tyro._typing.TypeForm[T][source]

Construct a Union type for defining subcommands that choose between defaults.

For example, when defaults is set to:

{
    "small": Config(...),
    "big": Config(...),
}

We return:

Union[
    Annotated[
        Config,
        tyro.conf.subcommand("small", default=Config(...))
    ],
    Annotated[
        Config,
        tyro.conf.subcommand("big", default=Config(...))
    ]
]

Direct use of typing.Union and tyro.conf.subcommand() should generally be preferred, but this function can be helpful for succinctness.

Warning

The type returned by this function can be safely used as an input to tyro.cli(), but for static analysis when used for annotations we recommend applying a TYPE_CHECKING guard:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    # Static type seen by language servers, type checkers, etc.
    SelectableConfig = Config
else:
    # Runtime type used by tyro.
    SelectableConfig = subcommand_type_from_defaults(...)
Parameters:
  • defaults (Mapping[str, T]) – A dictionary of default subcommand instances.

  • descriptions (Mapping[str, str]) – A dictionary conttaining descriptions for helptext.

  • prefix_names (bool) – Whether to prefix subcommand names.

  • sort_subcommands (bool) – If True, sort the subcommands alphabetically by name.

Returns:

A subcommand type, which can be passed to tyro.cli().

Return type:

tyro._typing.TypeForm[T]

tyro.extras.literal_type_from_choices(choices: Iterable[T]) tyro._typing.TypeForm[T][source]

Generate a typing.Literal type that constrains values to a set of choices.

Using Literal[...] directly should generally be preferred, but this function can be helpful when choices are generated dynamically.

Warning

The type returned by this function can be safely used as an input to tyro.cli(), but for static analysis when used for annotations we recommend applying a TYPE_CHECKING guard:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    # Static type seen by language servers, type checkers, etc.
    Color = str
else:
    # Runtime type used by tyro.
    Color = literal_type_from_choices(["red", "green", "blue"])
Parameters:

choices (Iterable[T]) – Options to choose from.

Returns:

A type that can be passed to tyro.cli().

Return type:

tyro._typing.TypeForm[T]

tyro.extras.from_yaml(cls: Type[DataclassType], stream: str | IO[str] | bytes | IO[bytes]) DataclassType[source]

Re-construct a dataclass instance from a yaml-compatible string, which should be generated from tyro.extras.to_yaml().

Warning

Deprecated. Serialization functionality is stable but deprecated. It may be removed in a future version of tyro.

As a secondary feature aimed at enabling the use of tyro.cli() for general configuration use cases, we also introduce functions for human-readable dataclass serialization: tyro.extras.from_yaml() and tyro.extras.to_yaml() attempt to strike a balance between flexibility and robustness — in contrast to naively dumping or loading dataclass instances (via pickle, PyYAML, etc), explicit type references enable custom tags that are robust against code reorganization and refactor, while a PyYAML backend enables serialization of arbitrary Python objects.

Parameters:
  • cls (Type[DataclassType]) – Type to reconstruct.

  • stream (Union[str, IO[str], bytes, IO[bytes]]) – YAML to read from.

Returns:

Instantiated dataclass.

Return type:

DataclassType

tyro.extras.to_yaml(instance: Any) str[source]

Serialize a dataclass; returns a yaml-compatible string that can be deserialized via tyro.extras.from_yaml().

Warning

Deprecated. Serialization functionality is stable but deprecated. It may be removed in a future version of tyro.

As a secondary feature aimed at enabling the use of tyro.cli() for general configuration use cases, we also introduce functions for human-readable dataclass serialization: tyro.extras.from_yaml() and tyro.extras.to_yaml() attempt to strike a balance between flexibility and robustness — in contrast to naively dumping or loading dataclass instances (via pickle, PyYAML, etc), explicit type references enable custom tags that are robust against code reorganization and refactor, while a PyYAML backend enables serialization of arbitrary Python objects.

Parameters:

instance (Any) – Dataclass instance to serialize.

Returns:

YAML string.

Return type:

str

class tyro.extras.SubcommandApp[source]

This class provides a decorator-based API for subcommands in tyro, inspired by click. Under-the-hood, this is a light wrapper over tyro.cli().

Example:

from tyro.extras import SubcommandApp

app = SubcommandApp()

@app.command
def greet(name: str, loud: bool = False):
    '''Greet someone.'''
    greeting = f"Hello, {name}!"
    if loud:
        greeting = greeting.upper()
    print(greeting)

@app.command(name="addition")
def add(a: int, b: int):
    '''Add two numbers.'''
    print(f"{a} + {b} = {a + b}")

if __name__ == "__main__":
    app.cli()

Usage:

python my_script.py greet Alice
python my_script.py greet Bob --loud
python my_script.py addition 5 3
command(func: CallableT) CallableT[source]
command(func: None = None, *, name: str | None = None) Callable[[CallableT], CallableT]

A decorator to register a function as a subcommand.

This method is inspired by Click’s @cli.command() decorator. It adds the decorated function to the list of subcommands.

Parameters:
  • func – The function to register as a subcommand. If None, returns a function to use as a decorator.

  • name – The name of the subcommand. If None, the name of the function is used.

cli(*, prog: str | None = None, description: str | None = None, args: Sequence[str] | None = None, use_underscores: bool = False, console_outputs: bool = True, config: Sequence[Any] | None = None, sort_subcommands: bool = False, registry: tyro.constructors.ConstructorRegistry | None = None) Any[source]

Run the command-line interface.

This method creates a CLI using tyro, with all subcommands registered using command().

Parameters:
  • prog (str | None) – The name of the program printed in helptext. Mirrors argument from argparse.ArgumentParser().

  • description (str | None) – Description text for the parser, displayed when the –help flag is passed in. If not specified, the class docstring is used. Mirrors argument from argparse.ArgumentParser().

  • args (Sequence[str] | None) – If set, parse arguments from a sequence of strings instead of the commandline. Mirrors argument from argparse.ArgumentParser.parse_args().

  • use_underscores (bool) – If True, use underscores as a word delimiter instead of hyphens. This primarily impacts helptext; underscores and hyphens are treated equivalently when parsing happens. We default helptext to hyphens to follow the GNU style guide. https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html

  • console_outputs (bool) – If set to False, parsing errors and help messages will be suppressed.

  • config (Sequence[Any] | None) – Sequence of config marker objects, from tyro.conf.

  • sort_subcommands (bool) – If True, sort the subcommands alphabetically by name.

  • registry (tyro.constructors.ConstructorRegistry | None) – A tyro.constructors.ConstructorRegistry instance containing custom constructor rules.

Return type:

Any

tyro.extras.subcommand_cli_from_dict(subcommands: Dict[str, Callable[Ellipsis, T]], *, prog: str | None = None, description: str | None = None, args: Sequence[str] | None = None, use_underscores: bool = False, console_outputs: bool = True, config: Sequence[tyro.conf._markers.Marker] | None = None, sort_subcommands: bool = False, registry: tyro.constructors.ConstructorRegistry | None = None) T[source]
tyro.extras.subcommand_cli_from_dict(subcommands: Dict[str, Callable[Ellipsis, Any]], *, prog: str | None = None, description: str | None = None, args: Sequence[str] | None = None, use_underscores: bool = False, console_outputs: bool = True, config: Sequence[tyro.conf._markers.Marker] | None = None, sort_subcommands: bool = False, registry: tyro.constructors.ConstructorRegistry | None = None) Any

Generate a subcommand CLI from a dictionary of functions.

For an input like:

tyro.extras.subcommand_cli_from_dict(
    {
        "checkout": checkout,
        "commit": commit,
    }
)

This is internally accomplished by generating and calling:

from typing import Annotated, Any, Union
import tyro

tyro.cli(
    Union[
        Annotated[
            Any,
            tyro.conf.subcommand(name="checkout", constructor=checkout),
        ],
        Annotated[
            Any,
            tyro.conf.subcommand(name="commit", constructor=commit),
        ],
    ]
)
Parameters:
  • subcommands – Dictionary that maps the subcommand name to function to call.

  • prog – The name of the program printed in helptext. Mirrors argument from argparse.ArgumentParser.

  • description – Description text for the parser, displayed when the –help flag is passed in. If not specified, f’s docstring is used. Mirrors argument from argparse.ArgumentParser.

  • args – If set, parse arguments from a sequence of strings instead of the commandline. Mirrors argument from argparse.ArgumentParser.parse_args().

  • use_underscores – If True, use underscores as a word delimeter instead of hyphens. This primarily impacts helptext; underscores and hyphens are treated equivalently when parsing happens. We default helptext to hyphens to follow the GNU style guide. https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html

  • console_outputs – If set to False, parsing errors and help messages will be supressed. This can be useful for distributed settings, where tyro.cli() is called from multiple workers but we only want console outputs from the main one.

  • config – Sequence of config marker objects, from tyro.conf.

  • registry – A tyro.constructors.ConstructorRegistry instance containing custom constructor rules.