I want to create some objects based on arguments in a yaml file. Everything was working fine, but now I want to supply the class with some options from which one should be chosen randomly. I thought I could use the __post_init__
method for this, but the learned, that this is intentionally not called because the use case is to serialize and deserialize objects.
Is there a way to tell ruamel to use the constructor of the class and call __post_init__
?
This is almost what I want, but I couldn't get it to work with ruamel despite it saying that it was tested using ruamel at the bottom:
My current setup is like this:
import random
from abc import ABC, abstractmethod
from dataclasses import dataclass
from ruamel.yaml import YAML, yaml_object
yaml = YAML()
@dataclass
class A(ABC):
some_var: str
options: list[str]
def __post_init__(self):
self.other_var = random.choice(self.options)
@yaml_object(yaml)
@dataclass
class B(A):
yaml_tag = "!B"
more: int
@yaml_object(yaml)
@dataclass
class C(A):
yaml_tag = "!C"
foo: list[int]
def __post_init__(self):
super().__post_init__()
self.bar = random.choice(self.foo)
# …
data = yaml.load("config.yml")
yaml to load:
test_classes:
- !B
some_var: abc123
options: ['X', 'Y', 'Z']
more: 7
- !C
some_var: abc123
options: ['X', 'Y', 'Z']
foo: [7, 12, 42]