I have the following code, using the hydra framework
# dummy_hydra.py
from dataclasses import dataclass
import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import DictConfig, OmegaConf
@dataclass
class Foo:
x: int = 0
y: int = 1
@dataclass
class Bar:
a: int = 0
b: int = 1
@dataclass
class FooBar:
foo: Foo
bar: Bar
cs = ConfigStore.instance()
cs.store(name="config_schema", node=FooBar)
@hydra.main(config_name="dummy_config", config_path=".", version_base=None)
def main(config: DictConfig):
config_obj: FooBar = OmegaConf.to_object(config)
print(config_obj)
if __name__ == '__main__':
main()
(This is a simplified code of my actual use case, of course)
As you can see, I have a nested dataclass - the FooBar
class contains instances of Foo
and Bar
. Both Foo
and Bar
have default attribute values. Hence, I thought I can define a yaml file that does not necessarily initializes Foo
and/or Bar
. Here's the file I use:
# dummy_config.yaml
defaults:
- config_schema
- _self_
foo:
x: 123
y: 456
When I run this code, surprisingly (?) it does not initialize Bar
(which is not mentioned in the yaml config file), but throws an error:
omegaconf.errors.MissingMandatoryValue: Structured config of type `FooBar` has missing mandatory value: bar
full_key: bar
object_type=FooBar
What's the proper way to use this class structure such that I don't need to explicitly initialize classes with non-mandatory fields (such as Bar
)?