简体   繁体   中英

Can I get access to the global configs from an arbitrary function in my code?

I apologize in advance if what I'm trying to do is an anti-pattern.

I would like to access my global configuration from somewhere in my code where it would be extremely cumbersome to pass the config object that the hydra-decorated main function uses.
I know that this is possible with the hydra-specific configs, using the HydraConfig object. Is there a similar construct for the application-specific configs? Thanks!

Is there a similar construct for the application-specific configs?

Nope, there is no such construct.

If you need access to global state, why not use a global variable?

# app.py
from typing import Optional

import hydra
from omegaconf import DictConfig

# global state
app_cfg: Optional[DictConfig] = None

def nested():
    global app_cfg
    assert app_cfg is not None
    print(f"{app_cfg.foo=}")

def fn():
    nested()

@hydra.main(config_path=None)
def app(cfg: DictConfig) -> None:
    global app_cfg
    app_cfg = cfg
    fn()

if __name__ == "__main__":
    app()
$ python app.py +foo=bar
app_cfg.foo='bar'

You can define a hydra config globally (eg, in the config.py file) and use it across multiple files by importing the config.

Check https://hydra.cc/docs/advanced/compose_api/#initialization-methods for more details.

File structure:

├── conf
│   └── config.yaml
├── config.py
├── main.py
└── utils.py

config.py

import hydra

hydra.initialize(version_base=None, config_path="conf")
cfg = hydra.compose(config_name="config")

main.py

from config import cfg
from utils import util_function


def main():
    print("Main cfg print\n", cfg)
    util_function()
    return


if __name__ == "__main__":
    main()

utils.py

from config import cfg


def util_function():
    print("Util cfg print\n", cfg)
    return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM