Menu

#355 Enhancement: Add support for Python's dataclass

resolved
nobody
None
minor
enhancement
2023-10-08
2020-08-30
No

According to this StackOverflow question: https://stackoverflow.com/questions/51529458/when-ruamel-yaml-loads-dataclass-from-string-post-init-is-not-called ruamel.yaml doesn't fully support Python's dataclasses. The call to __post_init__ is missing.

I also checked the change logs of this projects, which is very details, but adding support for dataclasses is not mentioned. Therefore I request to add this support :).

Support can be implemented in 2 steps:
1. if the object is a data class (dataclasses.is_dataclass(obj)) and __post_init__ is defined, then call it.
2. if a field in a dataclass is typed as InitVar, then pass these parameters to __post_init__
See https://dev.to/furkan_kalkan1/a-fully-automated-metadata-objects-with-python-37s-brand-new-dataclass-library-492i => Part 3: Make our hands dirtier; add post_init only pseudo fields

Kind regards
Patrick

Discussion

  • sigma67

    sigma67 - 2023-08-11

    Is this being considered for implementation?

     
  • Anthon van der Neut

    Probably not in the base packages, but it could be added as a plugin. I would have to review (and update) the answer on the SO issue, but since that answer has not been accepted, I am not even sure it solves the OP's issue as is. Did you use that?

     
  • sigma67

    sigma67 - 2023-09-29

    I think the suggestion in the top SO answer is a reasonable one:

    Of course code for making a call to __post_init_() could be added to ruamel.yaml's Python object constructors, preferably after a test if something was created using @dataclass, as otherwise a non Data-Class class, that happens to have such a method named __post_init_, will all of a sudden have that method called during loading.

    That would enable users of dataclasses to use @yaml_object

     
  • Anthon van der Neut

    • status: open --> resolved
     
  • Anthon van der Neut

    The initial support for this is there, post_init() is called on registered dataclasses that get loaded.
    InitVar is now specifically supported

     

    Last edit: Anthon van der Neut 2023-10-04
  • sigma67

    sigma67 - 2023-10-08

    Awesome, thanks for addressing this

     

Log in to post a comment.