简体   繁体   English

Python - Hydra - 获取子模块中的配置

[英]Python - Hydra - Obtaining configuration in sub-module

Question问题

I am currently having trouble with getting hydra to work when not using @hydra.main in the main.py script (refer to error section).main.py脚本中不使用@hydra.main时,我目前无法让 hydra 工作(请参阅错误部分)。 I have tried the compose API, but that prevents me from using most of the functionality that hydra provides.我已经尝试过撰写 API,但这使我无法使用 hydra 提供的大部分功能。 I am unsure what I am trying to achieve is possible.我不确定我想要实现的目标是否可行。

Current Configuration Structure当前配置结构

Project Root
|
├── config
│   ├── default.yaml
│   ├── configuration1.yaml
│   └── configuration2.yaml
└── src
     ├── utils
     │   └── initialise.py
     └── main.py

Code代码

initialise.py初始化.py

import hydra
import omegaconf

CONFIG = None

@hydra.main(version_base=None, config_path='../../config', config_name='default')
def init_configs(cfg: omegaconf.DictConfig) -> None:

    global CONFIG
    CONFIG = cfg

    # Other initialisation code here.   

init_configs()

main.py主文件

from utils import initialise

print(initialise.CONFIG)

Error错误

Primary config module 'config' not found.
Check that it's correct and contains an __init__.py file

This is an attempt to implement an many anti-patterns.这是实现许多反模式的尝试。

@hydra.main() is designed to be your entry point. @hydra.main()旨在成为您的入口点。 Using it a utility function is wrong.使用它的实用程序 function 是错误的。

  1. Hydra config composition is very expressive. Hydra 配置组合非常富有表现力。 Allow Hydra to fully initialize your config.允许 Hydra 完全初始化您的配置。 Do not "initialize" it further.不要进一步“初始化”它。 This is preventing overriding things from the command line.这可以防止从命令行覆盖事物。
  2. Do not pass your config via a global.不要通过全局传递您的配置。 Pass individual config nodes to sub modules/functions.将单个配置节点传递给子模块/功能。 If you need to access the same config variable from many functional modules use interpolation ( key: ${foo.bar} ).如果您需要从许多功能模块访问相同的配置变量,请使用插值key: ${foo.bar} )。
  3. Attempting to reuse the entry point is a cause of many issues.尝试重用入口点是许多问题的原因。 You didn't write it explicitly, but your code smells a bit like an attempt to reuse the entry point.您没有明确地编写它,但您的代码闻起来有点像尝试重用入口点。 Don't be afraid to have as many @hydra.main() entry points as you have runnable modules不要害怕拥有与可运行模块一样多的@hydra.main()入口点

If you insist on having a config initialization utility, you need to let go of @hydra.main() and use the compose API.如果您坚持使用配置初始化实用程序,则需要让@hydra.main()的 go 并使用 compose API。 You can also combine the two but my recommendation to just let hydra.main() compose your config.您也可以将两者结合起来,但我的建议是让 hydra.main() 组成您的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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