-
I am trying to lazily instantiate a class (from multiple options) which requires a certain object, that only becomes available after an event. Imagine something liks this:
How can I achieve such thing in Hydra? I want to indicate what class is `optim_params["cls"]. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If you know ahead of time what the type will be, you could register an OmegaConf custom resolver like this: from omegaconf import OmegaConf
class Foo:
...
def get_Foo():
return Foo
OmegaConf.register_new_resolver("getFoo", get_Foo)
yaml_data = """
cls: ${getFoo:}
"""
optim_params = OmegaConf.create(yaml_data)
print(optim_params.cls) # prints <class '__main__.Foo'>
print(type(optim_params.cls)) # prints <class 'type'> If you do not know the class ahead of time, you can try registering the from omegaconf import OmegaConf
from hydra.utils import get_class
class Foo1:
...
class Foo2:
...
OmegaConf.register_new_resolver("getClass", get_class)
yaml_data = """
cls1: ${getClass:__main__.Foo1}
cls2: ${getClass:${indirection}}
indirection: __main__.Foo2
"""
optim_params = OmegaConf.create(yaml_data)
print(optim_params.cls1) # prints <class '__main__.Foo1'>
print(optim_params.cls2) # prints <class '__main__.Foo2'> In general, OmegaConf's resolvers are a good way to handle "lazy computation" use-cases like this one. |
Beta Was this translation helpful? Give feedback.
If you know ahead of time what the type will be, you could register an OmegaConf custom resolver like this:
If you do not know the class ahead of time, you can try registering the
hydra.utils.get_class
method as a custom resolver: