YAML roundtrip not working correctly
See original GitHub issueHello, I am using hydra-zen to save config yaml files, ship them over to another system, and then load them back in and instantiate them. However, load_from_yaml
is not working as expected - it loads back in a DictConfig
rather than a hydrazen type
and thus none of the type validation + coercion works when instantiating the loaded yaml. This is particularly an issue for enum types.
Repro:
import omegaconf
from omegaconf import MISSING, OmegaConf
import dataclasses
from enum import Enum
from hydra_zen import instantiate, builds, save_as_yaml, load_from_yaml, to_yaml
class Color(Enum):
red = "RED"
blue = "BLUE"
@dataclasses.dataclass
class Example:
color: Color = MISSING
number: int = MISSING
built = builds(Example, color="blue", number="3")
print(type(built))
print(built)
print(instantiate(built))
save_as_yaml(built, "saved.yaml")
loaded = load_from_yaml("saved.yaml")
print()
print(type(loaded))
print(loaded)
print(instantiate(loaded))
The first 3 prints make sense:
<class 'type'>
<class 'types.Builds_Example'>
Example(color=<Color.blue: 'BLUE'>, number=3)
Proper type validation and coercion is done. When the yaml is saved and loaded back in however, type validation + coercion does not happen, since load_from_yaml
returns a DictConfig
rather than a type
. The results of instantiate
do not match. From the last 3 prints:
<class 'omegaconf.dictconfig.DictConfig'>
{'_target_': '__main__.Example', 'color': 'blue', 'number': 3}
Example(color='blue', number=3)
As you can see, Example
is instantiated with the string blue
rather than the enum <Color.blue: 'BLUE'>
.
Issue Analytics
- State:
- Created 10 months ago
- Comments:5 (2 by maintainers)
@Jasha10 thank you for this suggestion - it does seem to address my cases. I guess the only inconvenience is that I need to have special handling via
builds
for enums. I will try it out in my project and re-open if I run into more errors. Appreciate all the help!One workaround, which does not rely on OmegaConf’s implicit conversion of
str
toEnum
, is to callbuilds(Color, value="BLUE")
so as to create an object whose_target_
points toColor
:I believe my proposal above should work around the 3 situations you mentioned, @petosa.