Hydra:从子节点插入变量



给定以下配置文件:

# foo/bar.yaml
_target_: ChildClass
a: 0
b: 1
# config.yaml
defaults:
- foo: bar.yaml
_target_: MainClass
c: 2
d: ${foo.a}  # this line doesn't work

我想构造一个MainClass类型的对象,它接受一个ChildClassstrong>ChildClass的一个参数也用于

MainClass如何使用参数插值读取子属性a

您的想法应该按原样运行。请确保您拥有Hydra版本>=1.1安装,并尝试一下:

# foo/bar.yaml
_target_: mod.ChildClass
a: 0
b: 1
# config.yaml
defaults:
- foo: bar.yaml
_target_: mod.MainClass
c: 2
d: ${foo.a}
# mod.py
class ChildClass:
def __init__(self, a, b):
print(f"Child {a=} {b=}")

class MainClass:
def __init__(self, c, d, foo):
print(f"Child {c=} {d=} {foo=}")
# app.py
import hydra
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf

@hydra.main(config_path=".", config_name="config")
def run(cfg: DictConfig):
instantiate(cfg)

if __name__ == "__main__":
run()
$ python app.py
Child a=0 b=1
Child c=2 d=0 foo=<mod.ChildClass object at 0x7f675436b130>

最新更新