tyro.extras
#
The tyro.extras
submodule contains helpers that complement tyro.cli()
.
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
, seepython -m rich.color
. Experimental.- Parameters:
accent_color (Optional[str]) –
- Return type:
None
- tyro.extras.get_parser(f: tyro._typing.TypeForm[OutT], *, prog: str | None = None, description: str | None = None, default: OutT | None = None, use_underscores: bool = False, console_outputs: bool = True) tyro._argparse.ArgumentParser [source]#
- tyro.extras.get_parser(f: Callable[Ellipsis, OutT], *, prog: str | None = None, description: str | None = None, default: OutT | None = None, use_underscores: bool = False, console_outputs: bool = True) tyro._argparse.ArgumentParser
Get the
argparse.ArgumentParser
object generated under-the-hood bytyro.cli()
. Useful for tools likesphinx-argparse
,argcomplete
, etc.For tab completion, we recommend using
tyro.cli()
‘s built-in--tyro-write-completion
flag.
- tyro.extras.subcommand_type_from_defaults(defaults: Mapping[str, T], descriptions: Mapping[str, str] = {}, *, prefix_names: bool = True) 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
andtyro.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.
- 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()
.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.Warning
Serialization functionality is stable but deprecated. It may be removed in a future version of
tyro
.- 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()
.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.Warning
Serialization functionality is stable but deprecated. It may be removed in a future version of
tyro
.- Parameters:
instance (Any) – Dataclass instance to serialize.
- Returns:
YAML string.
- Return type:
str
- 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) 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) 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 fromargparse.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