hydra_zen.hydrated_dataclass#

hydra_zen.hydrated_dataclass(target, *pos_args, zen_partial=None, zen_wrappers=(), zen_meta=None, populate_full_signature=False, hydra_recursive=None, hydra_convert=None, zen_convert=None, init=True, repr=True, eq=True, order=False, unsafe_hash=True, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)[source]#

A decorator that uses builds to create a dataclass with the appropriate Hydra-specific fields for specifying a targeted config [1].

This provides similar functionality to builds, but enables a user to define a config explicitly using the dataclasses.dataclass() syntax, which can enable enhanced static analysis of the resulting config.

Parameters:
hydra_targetT (Callable)

The target-object to be configured. This is a required, positional-only argument.

*pos_argsSupportedPrimitive

Positional arguments passed as hydra_target(*pos_args, ...) upon instantiation.

Arguments specified positionally are not included in the dataclass’ signature and are stored as a tuple bound to in the _args_ field.

zen_partialOptional[bool]

If True, then the resulting config will instantiate as functools.partial(hydra_target, *pos_args, **kwargs_for_target) rather than hydra_target(*pos_args, **kwargs_for_target). Thus this enables the partial-configuration of objects.

Specifying zen_partial=True and populate_full_signature=True together will populate the config’s signature only with parameters that: are explicitly specified by the user, or that have default values specified in the target’s signature. I.e. it is presumed that un-specified parameters that have no default values are to be excluded from the config.

zen_wrappersNone | Callable | Builds | InterpStr | Sequence[None | Callable | Builds | InterpStr]

One or more wrappers, which will wrap hydra_target prior to instantiation. E.g. specifying the wrappers [f1, f2, f3] will instantiate as:

f3(f2(f1(hydra_target)))(*args, **kwargs)

Wrappers can also be specified as interpolated strings [2] or targeted configs.

zen_metaOptional[Mapping[str, SupportedPrimitive]]

Specifies field-names and corresponding values that will be included in the resulting config, but that will not be used to builds <hydra_target> via instantiation. These are called “meta” fields.

populate_full_signaturebool, optional (default=False)

If True, then the resulting config’s signature and fields will be populated according to the signature of hydra_target; values also specified in **kwargs_for_target take precedent.

This option is not available for objects with inaccessible signatures, such as NumPy’s various ufuncs.

zen_convertOptional[ZenConvert]

A dictionary that modifies hydra-zen’s value and type conversion behavior. Consists of the following optional key-value pairs (hydra_zen.typing.ZenConvert):

  • dataclassbool (default=True):

    If True any dataclass type/instance without a _target_ field is automatically converted to a targeted config that will instantiate to that type/instance. Otherwise the dataclass type/instance will be passed through as-is.

hydra_recursiveOptional[bool], optional (default=True)

If True, then Hydra will recursively instantiate all other hydra-config objects nested within this config [3].

If None, the _recursive_ attribute is not set on the resulting config.

  • "none": No conversion occurs; omegaconf containers are passed through (Default)

  • "partial": DictConfig and ListConfig objects converted to dict and list, respectively. Structured configs and their fields are passed without conversion.

  • "all": All passed objects are converted to dicts, lists, and primitives, without a trace of OmegaConf containers.

If None, the _convert_ attribute is not set on the resulting config.

hydra_convertOptional[Literal[“none”, “partial”, “all”, “object”]], optional (default=”none”)

Determines how Hydra treats the non-primitive, omegaconf-specific objects during instantiateion [3].

  • "none": No conversion occurs; omegaconf containers are passed through (Default)

  • "partial": DictConfig and ListConfig objects converted to dict and list, respectively. Structured configs and their fields are passed without conversion.

  • "all": All passed objects are converted to dicts, lists, and primitives, without a trace of OmegaConf containers.

  • "object": Passed objects are converted to dict and list. Structured Configs are converted to instances of the backing dataclass / attr class.

If None, the _convert_ attribute is not set on the resulting config.

initbool, optional (default=True)

If true (the default), a __init__() method will be generated. If the class already defines __init__(), this parameter is ignored.

reprbool, optional (default=True)

If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10).

eqbool, optional (default=True)

If true (the default), an __eq__() method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type.

orderbool, optional (default=False)

If true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised.

If the class already defines any of __lt__(), __le__(), __gt__(), or __ge__(), then TypeError is raised.

unsafe_hashbool, optional (default=False)

If False (the default), a __hash__() method is generated according to how eq and frozen are set.

If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() ` will be set to `None, marking it unhashable. If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object, this means it will fall back to id-based hashing).

frozenbool, optional (default=False)

If true (the default is False), assigning to fields will generate an exception. This emulates read-only frozen instances.

match_argsbool, optional (default=True)

(New in version 3.10) If true (the default is True), the __match_args__ tuple will be created from the list of parameters to the generated __init__() method (even if __init__() is not generated, see above). If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.

kw_onlybool, optional (default=False)

(New in version 3.10) If true (the default value is False), then all fields will be marked as keyword-only.

slotsbool, optional (default=False)

(New in version 3.10) If true (the default is False), __slots__ attribute will be generated and new class will be returned instead of the original one. If __slots__ is already defined in the class, then TypeError is raised.

weakref_slotbool, optional (default=False)

(New in version 3.11) If true (the default is False), add a slot named “__weakref__”, which is required to make an instance weakref-able. It is an error to specify weakref_slot=True without also specifying slots=True.

Raises:
hydra_zen.errors.HydraZenUnsupportedPrimitiveError

The provided configured value cannot be serialized by Hydra, nor does hydra-zen provide specialized support for it. See Configuration-Value Types Supported by Hydra and hydra-zen for more details.

See also

builds

Create a targeted structured config designed to “build” a particular object.

Notes

Unlike builds, hydrated_dataclass enables config fields to be set explicitly with custom type annotations. Additionally, the resulting config’ attributes can be analyzed by static tooling, which can help to warn about errors prior to running one’s code.

For details of the annotation SupportedPrimitive, see Configuration-Value Types Supported by Hydra and hydra-zen.

References

Examples

Basic usage

>>> from hydra_zen import hydrated_dataclass, instantiate

Here, we specify a config that is designed to “build” a dictionary upon instantiation

>>> @hydrated_dataclass(target=dict, frozen=True)
... class DictConf:
...     x: int = 2
...     y: str = 'hello'
>>> instantiate(DictConf(x=10))  # override default `x`
{'x': 10, 'y': 'hello'}
>>> d = DictConf()
>>> # Static type checker marks the following as
>>> # an error because `d` is frozen.
>>> d.x = 3  # type: ignore
FrozenInstanceError: cannot assign to field 'x'

For more detailed examples, refer to builds.