0

Given the following config files:

# 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

I would like to construct an object of type MainClass, which takes an object of type ChildClass.
One of the arguments of ChildClass is also used in the constructor of MainClass.

How can I read the child property a using argument interpolation?

miccio
  • 133
  • 1
  • 10

1 Answers1

0

Your idea should work as-is. Please make sure that you have Hydra version >= 1.1 installed, and give this a try:

# 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>
Jasha
  • 5,507
  • 2
  • 33
  • 44