Juliana Xavier
Juliana Xavier

Reputation: 98

How to set new parameters to Hydra config file at runtime?

Consider

import hydra
from omegaconf import OmegaConf

@hydra.main(config_path="path/to/your/config_directory", config_name="config")
def main(cfg):
    print("hello world!")

# Call the function
if __name__ == "__main__":
    main()

Due to limitation in my application, I need to define configuration parameters to cfg at runtime. I thought about doing something as simple as cfg.new_parameter = "hello new parameter", but I prompts

omegaconf.errors.ConfigAttributeError: Key 'new_parameter' is not in struct

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/tapyu/.cache/pypoetry/virtualenvs/tscnn-zfTdj8bO-py3.10/lib/python3.10/site-packages/omegaconf/dictconfig.py", line 337, in __setattr__
    raise e
  <... full traceback see edit history ...>
 # set env var OC_CAUSE=1 for full trace
omegaconf.errors.ConfigAttributeError: Key 'new_parameter' is not in struct
    full_key: new_parameter
    object_type=dict

How to set new parameters to Hydra config file at runtime?

Upvotes: 0

Views: 385

Answers (1)

Daraan
Daraan

Reputation: 3780

You can use open_dict

import hydra
from omegaconf import OmegaConf, open_dict

@hydra.main(config_path="path/to/your/config_directory", config_name="config")
def main(cfg):
    with open_dict(cfg):
       cfg.new_key = value

Upvotes: 0

Related Questions