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.get_parser(f: Type[OutT], *, prog: None | str = None, description: None | str = None, default: OutT | tyro._singleton.NonpropagatingMissingType | tyro._singleton.PropagatingMissingType = MISSING_NONPROP, use_underscores: bool = False, console_outputs: bool = True, add_help: bool = True, config: None | Sequence[tyro.conf._markers.Marker] = None, registry: None | tyro.constructors.ConstructorRegistry = None) tyro._backends._argparse.ArgumentParser[source]¶
- tyro.extras.get_parser(f: Callable[Ellipsis, OutT], *, prog: None | str = None, description: None | str = None, default: OutT | tyro._singleton.NonpropagatingMissingType | tyro._singleton.PropagatingMissingType = MISSING_NONPROP, use_underscores: bool = False, console_outputs: bool = True, add_help: bool = True, config: None | Sequence[tyro.conf._markers.Marker] = None, registry: None | tyro.constructors.ConstructorRegistry = None) tyro._backends._argparse.ArgumentParser
Get an
argparse.ArgumentParserobject that approximates the CLI generated bytyro.cli(). Useful for tools likesphinx-argparse,argcomplete, etc.Deprecated since version 1.0.0: This function is deprecated and will be removed in a future version.
Note
The returned parser uses argparse-style subparsers, which is less flexible than tyro’s subcommand parser.
For tab completion, we recommend using
tyro.cli()’s built-in--tyro-write-completionflag.- 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.
add_help – Add a -h/–help option to the parser. This mirrors the argument from
argparse.ArgumentParser().config – A sequence of configuration marker objects from
tyro.conf.registry – A
tyro.constructors.ConstructorRegistryinstance containing custom constructor rules.
- tyro.extras.set_accent_color(accent_color: Literal[black, red, green, yellow, blue, magenta, cyan, white, bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white] | None) None[source]¶
Set an accent color to use in help messages. Experimental.
- Parameters:
accent_color (Literal[black, red, green, yellow, blue, magenta, cyan, white, bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white] | None)
- Return type:
None
- 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, add_help: 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 seetyro.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.
add_help (bool) – Add a -h/–help option to the parser. This mirrors the argument from argparse.ArgumentParser().
config (Sequence[Any] | None) – Sequence of config marker objects, from tyro.conf. We include
tyro.conf.AvoidSubcommandsby default.sort_subcommands (bool) – If True, sort the subcommands alphabetically by name.
registry (tyro.constructors.ConstructorRegistry | None) – A
tyro.constructors.ConstructorRegistryinstance 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) Type[T][source]¶
Construct a Union type for defining subcommands that choose between defaults.
For example, when
defaultsis 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.Unionandtyro.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:
- Returns:
A subcommand type, which can be passed to
tyro.cli().- Return type:
Type[T]
- tyro.extras.literal_type_from_choices(choices: Iterable[T]) Type[T][source]¶
Generate a
typing.Literaltype 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:
Type[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()andtyro.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.
- 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()andtyro.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:
- class tyro.extras.SubcommandApp[source]¶
This class provides a decorator-based API for subcommands in
tyro, inspired by Typer and cyclopts. Under-the-hood, this is a light wrapper overtyro.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", aliases=["sum"]) def add(a: int, b: int): '''Add two numbers.''' print(f"{a} + {b} = {a + b}") if __name__ == "__main__": app.cli()
Subcommand groups can be nested by registering one
SubcommandAppas a subcommand on another:db = SubcommandApp() @db.command def migrate(): ... @db.command def seed(): ... app = SubcommandApp() app.command(db, name="db") # `mycli db migrate`, `mycli db seed`
To make one subcommand the default when no subcommand is given, pass
is_default=True:@app.command(is_default=True) def run(name: str = "world"): print(f"hello {name}") # `mycli` runs `run("world")`; `mycli --name alice` runs `run("alice")`; # `mycli run --name alice` also works.
Usage:
python my_script.py greet Alice python my_script.py greet Bob --loud python my_script.py addition 5 3 python my_script.py sum 5 3 # via alias
- command(func: CallableT) CallableT[source]¶
- command(func: None = None, *, name: str | None = None, aliases: Sequence[str] | None = None, help: str | None = None, is_default: bool = False) Callable[[CallableT], CallableT]
- command(func: SubcommandApp, *, name: str | None = None, aliases: Sequence[str] | None = None, help: str | None = None, is_default: bool = False) SubcommandApp
Register a function or nested
SubcommandAppas a subcommand.This method is inspired by Typer’s
@app.command()and cyclopts’s@app.command()decorators.- Parameters:
func – The function (or
SubcommandAppinstance) to register. IfNone, returns a decorator.name – Name of the subcommand. Defaults to the function’s
__name__. Required when registering aSubcommandApp(since the app has no name of its own).aliases – Alternative names that resolve to the same subcommand. For example,
aliases=["sum"]lets users invokeaddas eitheraddorsum.help – Override the helptext for this subcommand. If not set, the function’s docstring (or nested app’s description) is used.
is_default – If
True, this subcommand becomes the implicit choice when the user invokes the CLI without naming a subcommand. At most one command perSubcommandAppmay set this.
- cli(*, prog: str | None = None, description: str | None = None, args: Sequence[str] | None = None, use_underscores: bool = False, console_outputs: bool = True, add_help: 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.
add_help (bool) – Add a -h/–help option to the parser. This mirrors the argument from argparse.ArgumentParser().
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.ConstructorRegistryinstance 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, add_help: 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, add_help: 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 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 – If set to
False, parsing errors and help messages will be supressed. This can be useful for distributed settings, wheretyro.cli()is called from multiple workers but we only want console outputs from the main one.add_help – Add a -h/–help option to the parser. This mirrors the argument from
argparse.ArgumentParser().config – Sequence of config marker objects, from
tyro.conf.registry – A
tyro.constructors.ConstructorRegistryinstance containing custom constructor rules.
- class tyro.extras.Verbosity[source]¶
Parsed verbosity counters from
-v/-qCLI flags.Drop into any tyro CLI struct to get standard
--verbose/-vand--quiet/-qcount flags that map to Pythonlogginglevels. The two flags are mutually exclusive.Example:
import logging import tyro from dataclasses import dataclass, field from tyro.extras import Verbosity @dataclass class Args: verbosity: Verbosity = Verbosity() args = tyro.cli(Args) logging.basicConfig(level=args.verbosity.log_level())
Default level mapping (baseline:
logging.WARNING):(none) → WARNING (30) -v → INFO (20) -vv → DEBUG (10) -q → ERROR (40) -qq → CRITICAL (50)
Values are clamped to the
DEBUG..``CRITICAL`` range.- verbose: typing_extensions.Annotated[tyro.conf.UseCounterAction[int], conf.arg(aliases=['-v'], help='Increase log verbosity.'), _verbosity_mutex] = 0¶
- quiet: typing_extensions.Annotated[tyro.conf.UseCounterAction[int], conf.arg(aliases=['-q'], help='Decrease log verbosity.'), _verbosity_mutex] = 0¶
- log_level(*, default: int = logging.WARNING) int[source]¶
Compute the effective logging level, clamped to
DEBUG..``CRITICAL``.Formula:
default + (quiet - verbose) * 10.- Parameters:
default (int) – Baseline logging level. Defaults to
logging.WARNING.- Returns:
An integer logging level suitable for
logging.basicConfig().- Return type: