I instantiate a hydra configuration from a python dataclass. For example
from dataclasses import dataclass
from typing import Any
from hydra.utils import instantiate
class Model():
def __init__(self, x=1):
self.x = x
@dataclass
class MyConfig:
model: Any
param: int
static_config = MyConfig(model=Model(x=2), param='whatever')
instantiated_config = instantiate(static_config)
Now, I would like to dump this configuration as a yaml, including the _target_
fields that Hydra uses to re-instantiate the objects pointed to inside the configuration. I would like to avoid having to write my own logic to write those _target_
fields, and I imagine there must be some hydra utility that does this, but I can't seem to find it in the documentation.
See OmegaConf.to_yaml
and OmegaConf.save
:
from omegaconf import OmegaConf
# dumps to yaml string
yaml_data: str = OmegaConf.to_yaml(my_config)
# dumps to file:
with open("config.yaml", "w") as f:
OmegaConf.save(my_config, f)
# OmegaConf.save can also accept a `str` or `pathlib.Path` instance:
OmegaConf.save(my_config, "config.yaml")
See also the Hydra-Zen project, which offers automatic generation of OmegaConf objects (which can be saved to yaml).