How can I use OmegaConf custom interpolation with Hydra?
Some background: One can define a custom interpolation for square root:
from omegaconf import OmegaConf
import math
OmegaConf.register_resolver("sqrt", lambda x: math.sqrt(float(x)))
And use it with this config.yaml:
foo: ${sqrt:9}
Loading and printing foo:
cfg = OmegaConf.load('config.yaml')
print(cfg.foo)
Outputs 3.0
When trying this with Hydra:
import hydra
@hydra.main(config_path="config.yaml")
def main(cfg):
  print(cfg.foo)
if __name__ == "__main__":
  main()
I get the following error:
Unsupported interpolation type sqrt
    full_key: foo
    reference_type=Optional[Dict[Any, Any]]
    object_type=dict
How can I register my resolver when using Hydra?
You can register your custom resolver ahead of time:
config.yaml:
foo: ${sqrt:9}
main.py:
from omegaconf import OmegaConf
import math
import hydra
OmegaConf.register_new_resolver("sqrt", lambda x: math.sqrt(float(x)))
@hydra.main(config_path=".", config_name="config")
def main(cfg):
  print(cfg.foo)
if __name__ == "__main__":
  main()
This will print 3.0.
This approach will work just as well with the Compose API. The evaluation of the custom resolver is happening when you access the node (lazily). You just need to register the resolver before you access it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With