Skip to content

Resolvers

The Python functions behind the resolvers of hya. See Resolvers to use them in a configuration.

Native resolvers

hya.resolvers

Implement some resolvers using features from standard libraries.

hya.resolvers.add_resolver

add_resolver(first: Any, *others: Any) -> Any

Return the addition of several objects.

The configuration nodes of the arguments are resolved first, at any depth, so adding lists of the configuration gives a new plain list, whatever the way they are written. The arguments are not modified: first is never extended in place.

Parameters:

Name Type Description Default
first Any

The first value to add.

required
*others Any

The other values to add.

()

Returns:

Type Description
Any

first + other1 + other2 + ... + otherN, computed with the

Any

resolved values. With a single argument, a list or a dictionary

Any

is a copy and any other object is returned as is. The elements of

Any

a list hold no interpolation.

Raises:

Type Description
TypeError

If the values cannot be added, for example a number and a string.

MissingMandatoryValue

If a node contains a missing value (???).

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.add:1,2}"})
>>> conf.key
3
>>> conf = OmegaConf.create({"key": "${hya.add:1,2,3,4}"})
>>> conf.key
10
>>> # Strings are concatenated
>>> OmegaConf.create({"key": "${hya.add:abc,def}"}).key
abcdef
>>> conf = OmegaConf.create({"x": [1, 2], "key": "${hya.add:${x},[3]}"})
>>> conf.key
[1, 2, 3]
>>> conf.x
[1, 2]
>>> # The interpolations of the values are resolved
>>> conf = OmegaConf.create({"a": 1, "x": ["${a}"], "key": "${hya.add:${x},[2]}"})
>>> conf.key
[1, 2]

hya.resolvers.ceildiv_resolver

ceildiv_resolver(dividend: float, divisor: float) -> float

Compute the ceiling division of two numbers.

Ceiling division rounds the result up, which is useful for calculating the minimum number of chunks needed to accommodate a given total. The type of the result follows //: an int for two integers (exact, whatever their size) and a float if one of them is a float (11.0, 4 gives 3.0).

Parameters:

Name Type Description Default
dividend float

The dividend (numerator).

required
divisor float

The divisor (denominator).

required

Returns:

Type Description
float

The ceiling of dividend / divisor, computed as

float

-(dividend // -divisor).

Raises:

Type Description
TypeError

If a value is not a number, for example a string.

ZeroDivisionError

If divisor is zero.

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.ceildiv:11,4}"})
>>> conf.key
3
>>> # Useful for calculating number of batches
>>> conf = OmegaConf.create({"batches": "${hya.ceildiv:100,32}"})
>>> conf.batches
4
>>> # The type of the result follows ``//``
>>> OmegaConf.create({"key": "${hya.ceildiv:11.0,4}"}).key
3.0

hya.resolvers.iter_join_resolver

iter_join_resolver(
    iterable: Iterable[Any], separator: str
) -> str

Convert all items in an iterable to strings and join them.

This resolver takes an iterable (e.g., list, tuple) and concatenates all elements into a single string, separated by the specified separator. The configuration nodes of the iterable are resolved first, at any depth. Each element is then converted to a string using str(), so a nested list is written as a Python list.

Parameters:

Name Type Description Default
iterable Iterable[Any]

Any iterable object where all the returned values are strings or can be converted to string. Common examples include lists, tuples, or OmegaConf ListConfig objects.

required
separator str

The separator string to use between the items. Can be any string including empty string, space, comma, etc.

required

Returns:

Type Description
str

A single string with all iterable elements joined by the separator.

Raises:

Type Description
TypeError

If iterable is not iterable.

AttributeError

If separator is not a string.

MissingMandatoryValue

If a node contains a missing value (???).

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.iter_join:[abc,2,def],-}"})
>>> conf.key
abc-2-def
>>> conf = OmegaConf.create({"path": "${hya.iter_join:[data,models,v1],/}"})
>>> conf.path
data/models/v1
>>> # The interpolations of nested values are resolved
>>> conf = OmegaConf.create(
...     {"a": 1, "x": [["${a}"], 2], "key": "${hya.iter_join:${x},-}"}
... )
>>> conf.key
[1]-2

hya.resolvers.mul_resolver

mul_resolver(first: Any, *others: Any) -> Any

Return the multiplication of several objects.

The arguments are not modified. The values are meant to be numbers: the repetition of a list of the configuration ([1, 2] * 2) is not supported.

Parameters:

Name Type Description Default
first Any

The first value to multiply.

required
*others Any

The other values to multiply.

()

Returns:

Type Description
Any

first * other1 * other2 * ... * otherN

Raises:

Type Description
TypeError

If the values cannot be multiplied, for example a list of the configuration and a number.

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.mul:1,2}"})
>>> conf.key
2
>>> conf = OmegaConf.create({"key": "${hya.mul:1,2,3}"})
>>> conf.key
6

hya.resolvers.path_resolver

path_resolver(path: str | PathLike[str]) -> Path

Return a resolved path object from a path or a file URL.

This resolver converts a string, or any path-like object (for example a pathlib.Path stored in the configuration), to a pathlib.Path object: it expands the user home directory (~) and resolves the path to an absolute path. A string that starts with file: (the scheme is case-insensitive) is read as a file URL: the path of the URL is used, with its percent-encoding (for example %20 for a space) decoded. In a URL, ? and # start a query and a fragment, so a file name that contains them is written %3F and %23. Any other URL with :// after a scheme of two characters or more (for example s3://bucket) is rejected: it is not a local path. Any other string is a plain path, written as is: ?, # and % are not interpreted.

Parameters:

Name Type Description Default
path str | PathLike[str]

The target path as a string or a path-like object, or a file: URL.

required

Returns:

Type Description
Path

A fully resolved pathlib.Path object with expanded user

Path

directory and converted to absolute path.

Raises:

Type Description
TypeError

If path is not a string or a path-like object.

RuntimeError

If the home directory of a ~ path cannot be determined, for example for an unknown user.

ValueError

If the path is empty (write . for the working directory); if a file: URL has no path, a host other than localhost (for example file://host/a), a query or a fragment (any ? or #, for example file:///data/run#1); or if the string is a URL with another scheme (scheme://...). A UnicodeDecodeError, a subclass of ValueError, is raised if the percent-encoding of a file: URL is not valid UTF-8.

Note

Within an OmegaConf interpolation, a path with a tilde (~) must be quoted (${hya.path:"~/data"}); unquoted, the interpolation is a grammar error.

Example
>>> from pathlib import Path
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.path:/my/path}"})
>>> conf.key
PosixPath('/my/path')
>>> conf = OmegaConf.create({"key": "${hya.path:file:///my/path%20to}"})
>>> conf.key
PosixPath('/my/path to')
>>> conf = OmegaConf.create({"key": '${hya.path:"~/my/path"}'})
>>> conf.key == Path("~/my/path").expanduser().resolve()
True
>>> conf = OmegaConf.create({"key": "${hya.path:${hya.path:/my/path}}"})
>>> conf.key
PosixPath('/my/path')

hya.resolvers.pi_resolver

pi_resolver() -> float

Return the value PI.

Returns:

Type Description
float

The value of PI.

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.pi:}"})
>>> conf.key
3.14159...

hya.resolvers.sha256_resolver

sha256_resolver(obj: Any) -> str

Compute the SHA-256 hash of the whole content of an object.

The configuration nodes of the object are resolved first, at any depth. A string is then hashed as is, so the result is the SHA-256 of the text, the same as other tools give. Any other value is hashed from its canonical JSON form: sorted keys, no space ([1,2], {"a":1,"b":2}, true, null) and non-ASCII characters escaped (\u00e9 for an e with an acute accent). In this form, a path or an enum is written as its string, except an enum that is also an int, a float or a str (for example an IntEnum), which is written as its value. Useful for generating consistent identifiers or cache keys from configuration values.

The hash does not keep the type of a value: the string [1] and the list [1] have the same hash, and so do an integer key and the same string key.

Parameters:

Name Type Description Default
obj Any

The object to compute the SHA-256 hash: a string, or a value with a JSON form (numbers, booleans, None, lists, tuples, dictionaries, ListConfig, DictConfig, paths and enums).

required

Returns:

Type Description
str

The SHA-256 hash as a hexadecimal string (64 characters).

Raises:

Type Description
TypeError

If a value has no JSON form (for example an array, a tensor, a data type, a set or bytes), if a key of a mapping is not a string, a number, a boolean or None, or if a mapping mixes key types that cannot be sorted.

ValueError

If a value or a key is a non-finite float (nan or inf), which has no JSON form.

MissingMandatoryValue

If a node contains a missing value (???).

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.sha256:mystring}"})
>>> conf.key
bd3ff47540b31e62d4ca6b07794e5a886b0f655fc322730f26ecd65cc7dd5c90
>>> # Useful for generating consistent IDs
>>> conf = OmegaConf.create({"id": "${hya.sha256:experiment_v1}"})
>>> # The order of the keys does not change the hash
>>> conf = OmegaConf.create(
...     {
...         "x": {"a": 1, "b": 2},
...         "y": {"b": 2, "a": 1},
...         "hx": "${hya.sha256:${x}}",
...         "hy": "${hya.sha256:${y}}",
...     }
... )
>>> conf.hx == conf.hy
True

Optional resolvers

hya.braceexpand

Implement a braceexpand resolver for brace expansion patterns.

This module provides OmegaConf resolvers that use the braceexpand library to expand string patterns with brace notation (similar to bash brace expansion). The resolver is always registered; the braceexpand package is needed only when it is called, and a missing package raises an error that says how to install it.

hya.braceexpand.braceexpand_resolver

braceexpand_resolver(pattern: str) -> list[str]

Return the list of the strings of a brace expansion of pattern.

This resolver expands a string with brace patterns similar to bash brace expansion, generating multiple strings from a single pattern. Useful for generating lists of similar configuration values.

Please check https://github.com/trendels/braceexpand for more information about the syntax.

Parameters:

Name Type Description Default
pattern str

Specifies the pattern of the brace expansion. Supports numeric ranges (e.g., "file{1..3}.txt"), character sequences (e.g., "{a,b,c}"), and nested patterns.

required

Returns:

Type Description
list[str]

The list of the strings resulting from the brace expansion of

list[str]

the pattern. It is a list (and not an iterator), so it has a

list[str]

length, can be indexed and can be read several times. The

list[str]

whole expansion is built at once.

Raises:

Type Description
RuntimeError

If the braceexpand package is not installed.

TypeError

If pattern is not a string.

ValueError

If the braces of the pattern are not balanced (braceexpand.UnbalancedBracesError, a subclass of ValueError).

Note

When using brace expansion patterns in OmegaConf, you need to quote the pattern string (${hya.braceexpand:"a{1,2}"}) to avoid conflicts with OmegaConf's own syntax for curly braces and commas. Without quotes, the braces and the commas must all be escaped.

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": '${hya.braceexpand:"file_{1..3}.txt"}'})
>>> list(conf.key)
['file_1.txt', 'file_2.txt', 'file_3.txt']
>>> len(conf.key)
3

hya.numpy

Implement NumPy resolvers for array creation and manipulation.

This module provides OmegaConf resolvers that use NumPy for array operations, allowing users to create NumPy arrays directly from configuration files. The numpy package is needed only when the resolver is called.

hya.numpy.to_array_resolver

to_array_resolver(
    data: ArrayLike, dtype: str | None = None
) -> ndarray

Implement a resolver to transform the input to a numpy.ndarray.

Parameters:

Name Type Description Default
data ArrayLike

Specifies the data to transform in numpy.ndarray: an array, a tensor (on the CPU and without gradient), or any other value compatible with numpy.array. The configuration nodes of a value are resolved first, at any depth, so a mapping node gives the same array as a literal mapping (an array of the data type object).

required
dtype str | None

The data type of the array, as a string that numpy.array accepts (for example "float32"). None lets NumPy infer the data type from the data.

None

Returns:

Type Description
ndarray

The input in a numpy.ndarray object. It is a copy: it does

ndarray

not share memory with an array or a tensor given as input, and

ndarray

it keeps the memory order of such an input.

Raises:

Type Description
RuntimeError

If the numpy package is not installed.

TypeError

If dtype is not a valid NumPy data type.

ValueError

If the data cannot be converted to an array, for example nested lists of different lengths, or a string with a numeric dtype.

MissingMandatoryValue

If a node contains a missing value (???).

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.np.array:[1, 2, 3]}"})
>>> conf.key
array([1, 2, 3])
>>> conf = OmegaConf.create({"key": "${hya.np.array:[1, 2, 3],float32}"})
>>> conf.key
array([1., 2., 3.], dtype=float32)
>>> # The interpolations of the data are resolved
>>> conf = OmegaConf.create({"a": 1, "x": ["${a}", 2], "key": "${hya.np.array:${x}}"})
>>> conf.key
array([1, 2])

hya.torch

Implement PyTorch resolvers for tensor creation and dtype handling.

This module provides OmegaConf resolvers that use PyTorch for tensor operations and data type specifications. The resolvers are always registered; the torch package is needed only when one of them is called, and a missing package raises an error that says how to install it. Users can create PyTorch tensors and specify dtypes directly from configuration files.

hya.torch.to_tensor_resolver

to_tensor_resolver(
    data: Any, dtype: dtype | str | None = None
) -> Tensor

Implement a resolver to transform the input to a torch.Tensor.

Parameters:

Name Type Description Default
data Any

Specifies the data to transform in torch.Tensor: a tensor, or a value compatible with torch.tensor. The configuration nodes of a value are resolved first, at any depth.

required
dtype dtype | str | None

The data type of the tensor: a torch.dtype (for example the output of the hya.torch.dtype resolver) or its name (for example "float32"). None keeps the data type of a tensor, and lets PyTorch infer the data type of any other value.

None

Returns:

Type Description
Tensor

The input in a torch.Tensor object. It is a copy: it does

Tensor

not share memory with a tensor given as input, and it does not

Tensor

require a gradient.

Raises:

Type Description
RuntimeError

If the torch package is not installed.

TypeError

If the data has a type that PyTorch does not support (for example a string), or if dtype is not a torch.dtype, a string or None.

ValueError

If dtype is a string that is not the name of a torch dtype, or if the data are nested lists of different lengths.

MissingMandatoryValue

If a node contains a missing value (???).

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.torch.tensor:[1,2,3,4,5]}"})
>>> conf.key
tensor([1, 2, 3, 4, 5])
>>> conf = OmegaConf.create({"key": "${hya.torch.tensor:[1,2,3],${hya.torch.dtype:float32}}"})
>>> conf.key
tensor([1., 2., 3.])
>>> # The data type can be given by its name
>>> conf = OmegaConf.create({"key": "${hya.torch.tensor:[1,2],float32}"})
>>> conf.key
tensor([1., 2.])
>>> # A tensor is copied
>>> conf = OmegaConf.create({"key": "${hya.torch.tensor:${hya.torch.tensor:[1,2]}}"})
>>> conf.key
tensor([1, 2])

hya.torch.torch_dtype_resolver

torch_dtype_resolver(target: str) -> dtype

Create a torch.dtype from its string representation.

This resolver converts a string name to the corresponding PyTorch data type object. The string must match an attribute name in the torch module that represents a dtype (e.g., "float32", "int64").

Parameters:

Name Type Description Default
target str

The target data type as a string. Must be a valid torch dtype attribute name such as "float", "float32", "float64", "int32", "int64", "bool", etc. The string should match the attribute name in torch (e.g., use "float32" not "torch.float32").

required

Returns:

Type Description
dtype

The corresponding torch.dtype object.

Raises:

Type Description
RuntimeError

If the torch package is not installed.

TypeError

If target is not a string.

ValueError

If the target string doesn't correspond to a valid torch dtype. The message lists the available dtype names, sorted. Through an interpolation, OmegaConf reports it as an InterpolationResolutionError.

Example
>>> import hya
>>> from omegaconf import OmegaConf
>>> conf = OmegaConf.create({"key": "${hya.torch.dtype:float}"})
>>> conf.key
torch.float32
>>> conf = OmegaConf.create({"key": "${hya.torch.dtype:int64}"})
>>> conf.key
torch.int64