Skip to content
Advertisement

Restrict possible values in hydra structured configs

I try to adopt my app for hydra framework. I use structured config schema and I want to restrict possible values for some fields. Is there any way to do that?

Here is my code:

my_app.py:

JavaScript

configs/config.yaml:

JavaScript

Advertisement

Answer

A few options:

1) If your acceptable values are enumerable, use an Enum type:

JavaScript

If no fancy logic is needed to validate some_value, this is the solution I would recommend.

2) If you are using yaml files, you can use OmegaConf to register a custom resolver:

JavaScript
JavaScript

When you access cfg.some_value in your python code, an AssertionError will be raised if the value does not agree with the check_some_value function.

3) After config composition is completed, you can call OmegaConf.to_object to create an instance of your dataclass. This means that the dataclass’s __post_init__ function will get called.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement