-
Suppose I have a config with classes that have subtypes, for example: from dataclasses import dataclass, field
import pytest
from omegaconf import OmegaConf, SCMode, ValidationError
@dataclass
class AbstractLetter:
pass
@dataclass
class A(AbstractLetter):
a: str = "a"
@dataclass
class B(AbstractLetter):
b: int = 2
@dataclass
class Config:
l: AbstractLetter = field(default_factory=A)
cfg = OmegaConf.structured(Config(l=B())) Now with this we get nice type checking at runtime if we assign the wrong thing to subfields of # Attempting to set the wrong type here does raise a ValidationError
with pytest.raises(ValidationError):
cfg.l.b = "hello" However, this is not the case if we serialize serialized = OmegaConf.to_yaml(cfg)
cfg2 = OmegaConf.create(serialized)
# This has no type information, so attempting to set the wrong type is completely fine.
cfg2.l.b = "hello" If OmegaConf.merge(OmegaConf.structured(Config), cfg2) How do I serialize in such a way that we can get back type information? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
One strategy is to use typed_cfg2 = OmegaConf.merge(Config, cfg2) |
Beta Was this translation helpful? Give feedback.
Sorry, I should have read the end of your question before answering.
This is a use case that would be covered by #144, which is not yet fully implemented.
The usage pattern would look something like this:
That
A | B
is a union type. Currently, runningOmegaConf.merge(ConfigUnion, cfg2)
gives the following error message:Unfortunately there's no good workaround for this as far as I'm aware.