:py:mod:`tyro.constructors` =========================== .. py:module:: tyro.constructors .. autoapi-nested-parse:: The :mod:`tyro.constructors` submodule exposes tyro's API for defining behavior for different types. .. warning:: This submodule is not needed for the majority of users. Package Contents ---------------- .. py:data:: MISSING :type: Any Sentinel value to mark default values as missing. Can be used to mark fields passed in via `default=` for `tyro.cli()` as required. When used, the 'missing' semantics propagate to children. For example, if we write: .. code-block:: python def main(inner: Dataclass = tyro.MISSING) -> None: ... tyro.cli(main) then all fields belonging to ``Dataclass`` will be marked as missing, even if a default exists in the dataclass definition. .. py:data:: MISSING_NONPROP :type: Any Non-propagating version of :data:`tyro.MISSING`. When used, the 'missing' semantics do not propagate to children. For example: .. code-block:: python def main(inner: Dataclass = tyro.MISSING_NONPROP) -> None: ... tyro.cli(main) is equivalent to: .. code-block:: python def main(inner: Dataclass) -> None: ... tyro.cli(main) where default values for fields belonging to ``Dataclass`` will be taken from the dataclass definition. .. py:class:: PrimitiveConstructorSpec Bases: :py:obj:`Generic`\ [\ :py:obj:`T`\ ] Specification for constructing a primitive type from a string. There are two ways to use this class: First, we can include it in a type signature via :class:`typing.Annotated`. This is the simplest for making local modifications to parsing behavior for individual fields. Alternatively, it can be returned by a rule in a :class:`ConstructorRegistry`. .. py:attribute:: nargs :type: int | tuple[int, Ellipsis] | Literal[*] Number of arguments required to construct an instance. If nargs is "*", then the number of arguments is variable. If nargs is a tuple, it represents multiple valid fixed argument counts (used for unions with different fixed nargs). .. py:attribute:: metavar :type: str Metavar to display in help messages. .. py:attribute:: instance_from_str :type: Callable[[list[str]], T] Given a list of string arguments, construct an instance of the type. The length of the list will match the value of nargs. .. py:attribute:: is_instance :type: Callable[[Any], bool | Literal[~]] Given an object instance, does it match this primitive type? This is used for specific help messages when both a union type is present and a default is provided. Can return "~" to signify that an instance is a "fuzzy" match, and should only be used if there are no other matches. This is used for numeric tower support. .. py:attribute:: str_from_instance :type: Callable[[T], list[str]] Convert an instance to a list of string arguments that would construct the instance. This is used for help messages when a default is provided. .. py:attribute:: choices :type: tuple[str, Ellipsis] | None Finite set of choices for arguments. .. py:class:: PrimitiveTypeInfo Information used to generate constructors for primitive types. .. py:attribute:: type :type: Type Annotated field type. Forward references, aliases, and type variables/parameters will have been resolved and runtime annotations (typing.Annotated) will have been stripped. .. py:attribute:: type_origin :type: Type | None The output of get_origin() on the static type. .. py:attribute:: markers :type: set[tyro.conf._markers.Marker] Set of tyro markers used to configure this field. .. py:method:: make(raw_annotation: Type | Callable, parent_markers: set[tyro.conf._markers.Marker], exclude_markers: set[tyro.conf._markers.Marker] | None = None) -> PrimitiveTypeInfo :staticmethod: .. py:exception:: UnsupportedTypeAnnotationError(message: tuple[tyro._fmtlib._Text, Ellipsis]) Bases: :py:obj:`Exception` Exception raised when a type annotation is not supported. .. py:class:: ConstructorRegistry Registry for rules that define how types are constructed from command-line arguments. The behavior of CLIs generated by tyro are based on two types of rules. *Primitive rules* should be a callable with the signature: .. code-block: python (type_info: PrimitiveTypeInfo) -> PrimitiveConstructorSpec | UnsupportedTypeAnnotationError | None where `None` is returned if the rule doesn't apply, and `UnsupportedTypeAnnotationError` is returned if the rule applies but an error was encountered. Each primitive rule defines behavior for a type that can be instantiated from a single command-line argument. *Struct rules* should be a callable with the signature: .. code-block: python (type_info: StructTypeInfo) -> StructConstructorSpec | None where `None` is returned if the rule doesn't apply. Each struct rule defines behavior for a type that can be instantiated from multiple command-line arguments. To activate a registry, pass it directly to :func:`tyro.cli`: .. code-block: python registry = ConstructorRegistry() tyro.cli(..., registry=registry) For backward compatibility, you can also use the context manager pattern, though the direct parameter approach is recommended: .. code-block: python registry = ConstructorRegistry() with registry: tyro.cli(...) .. py:method:: primitive_rule(rule: PrimitiveSpecRule) -> PrimitiveSpecRule Define a rule for constructing a primitive type from a string. The most recently added rule will be applied first. Custom primitive rules will take precedence over both default primitive rules and struct rules .. py:method:: struct_rule(rule: StructSpecRule) -> StructSpecRule Define a rule for constructing a primitive type from a string. The most recently added rule will be applied first. .. py:method:: get_primitive_spec(type_info: tyro.constructors._primitive_spec.PrimitiveTypeInfo, nondefault_only: bool = False) -> tyro.constructors._primitive_spec.PrimitiveConstructorSpec | tyro.constructors._primitive_spec.UnsupportedTypeAnnotationError :classmethod: Get a constructor specification for a given type. .. py:method:: get_struct_spec(type_info: tyro.constructors._struct_spec.StructTypeInfo) -> tyro.constructors._struct_spec.StructConstructorSpec | tyro.constructors._struct_spec.InvalidDefaultInstanceError | None :classmethod: Get a constructor specification for a given type. :returns: - StructConstructorSpec if the type can be handled as a struct. - InvalidDefaultInstanceError if the type can be handled, but the provided default instance is incompatible with the type. - None if the type cannot be handled as a struct (no matching rule found). .. py:method:: __enter__() -> None .. py:method:: __exit__(*args: Any) -> None .. py:class:: StructConstructorSpec Specification for a struct type, which is broken down into multiple fields. Each struct type is instantiated by calling an ``instantiate(**kwargs)`` function with keyword a set of keyword arguments. Unlike :class:`PrimitiveConstructorSpec`, there is only one way to use this class. It must be returned by a rule in :class:`ConstructorRegistry`. .. py:attribute:: instantiate :type: Callable[Ellipsis, Any] Function to call to instantiate the struct. .. py:attribute:: fields :type: tuple[StructFieldSpec, Ellipsis] Fields used to construct the callable. Each field is used as a keyword argument for the ``instantiate(**kwargs)`` function. .. py:class:: StructFieldSpec Behavior specification for a single field in our callable. .. py:attribute:: name :type: str The name of the field. This will be used as a keyword argument for the struct's associated ``instantiate(**kwargs)`` function. .. py:attribute:: type :type: Type The type of the field. Can be either a primitive or a nested struct type. .. py:attribute:: default :type: Any The default value of the field. .. py:attribute:: helptext :type: str | Callable[[], str | None] | None Helptext for the field. .. py:attribute:: is_default_overridden :type: None Deprecated. No longer used. .. py:class:: StructTypeInfo Information used to generate constructors for struct types. .. py:attribute:: type :type: Type The type of the (potential) struct. .. py:attribute:: markers :type: tuple[Any, Ellipsis] Markers from :mod:`tyro.conf` that are associated with this field. .. py:attribute:: default :type: Any The default value of the struct, or a member of :data:`tyro.constructors.MISSING_AND_MISSING_NONPROP` if not present. In a function signature, this is ``X`` in ``def main(x=X): ...``. This can be useful for populating the default values of the struct. .. py:attribute:: in_union_context :type: bool Flag indicating whether this type is being evaluated as part of a union. When True, allows collection types like List[Struct] or Dict[str, Struct] without defaults to be treated as struct types for subcommand creation. .. py:method:: make(f: Type | Callable, default: Any, in_union_context: bool) -> StructTypeInfo :staticmethod: