Closed LaurentBergeron closed 1 year ago
Main issue with implementing this is registering "representers" for dataclasses... since both PyYAML and Ruamel YAML don't allow implicitly passing subclasses, this is a problem that would require one of the following:
@dataclass
, which is suuuuper hacky...).dict()
results and converting dataclasses into their YamlModel equivalents (oof!).I don't particularly like the 1st fix, because it's very fragile and requires a certain import order (i.e. you must always import pydantic_yaml
within your dataclass definitions). 1st and 2nd solution still don't fix parsing these (I'm sure there would be issues, ha). And the 3rd solution is what seems like I'll have to do eventually, but it needs to be well-designed and well-tested, which I do not have time for. :(
Gladly taking any suggestions or ideas I might have missed, though!
I wonder if we could use this: https://yaml.readthedocs.io/en/latest/dumpcls.html
It would work something like this:
pydantic_yaml.dataclasses.dataclass
around pydantic.dataclasses.dataclass
YAML()
instanceto_yaml
and from_yaml
methods to the dataclass (not even sure this would be necessary, but the option is there just in case)Note that you can now do this with json_encoders
(Pydantic v1) or @field_serializer
(Pydantic v2) for specific fields.
With Pydantic v2 you can also use RootModel to dump your model:
obj = YourType()
to_yaml_str(RootModel[YourType](obj))
I'll add this to docs.
Added to docs. Top-level available since version 1.1.0 🎉
It would be nice to add support for dataclasses
For example:
currently raises with: