Skip to content Skip to sidebar Skip to footer

How To Get A Hydra Config Without Using @hydra.main()

Let's say we have following setup (copied & shortened from the Hydra docs): Configuration file: config.yaml db: driver: mysql user: omry pass: secret Python file: my_app

Solution 1:

Use the Compose API:

from hydra import compose, initialize
from omegaconf import OmegaConf

initialize(config_path="conf", job_name="test_app")
cfg = compose(config_name="config", overrides=["db=mysql", "db.user=me"])
print(OmegaConf.to_yaml(cfg))

This will only compose the config and will not have side effects like changing the working directory or configuring the Python logging system.

Solution 2:

None of the above solutions worked for me. They gave errors:

'builtin_function_or_method' object has no attribute 'code'

and

GlobalHydra is already initialized, call Globalhydra.instance().clear() if you want to re-initialize

I dug further into hydra and realised I could just use OmegaConf to load the file directly. You don't get overrides but I'm not fussed about this.

importomegaconfcfg= omegaconf.OmegaConf.load(path)

Solution 3:

I found a rather ugly answer but it works - if anyone finds a more elegant solution please let us know!

We can use a closure or some mutable object. In this example we define a list outside and append the config object:

import hydra
c = []
hydra.main(config_path="config.yaml")(c.append)()
cfg = c[0]
print(cfg.pretty())

Solution 4:

anther ugly answer, but author said this may be crush in next version

Blockquote

from omegaconf import DictConfig
from hydra.utils import instantiate
from hydra._internal.utils import _strict_mode_strategy, split_config_path, create_automatic_config_search_path
from hydra._internal.hydra import Hydra
from hydra.utils import get_classclass SomeThing:
...
defload_from_yaml(self, config_path, strict=True):
    config_dir, config_file = split_config_path(config_path)
    strict = _strict_mode_strategy(strict, config_file)
    search_path = create_automatic_config_search_path(
        config_file, None, config_dir
    )
    hydra = Hydra.create_main_hydra2(
        task_name='sdfs', config_search_path=search_path, strict=strict
    )
    config = hydra.compose_config(config_file, [])
    config.pop('hydra')
    self.config = config
    print(self.config.pretty())

Post a Comment for "How To Get A Hydra Config Without Using @hydra.main()"