rnag / dataclass-wizard

A simple, yet elegant, set of wizarding tools for interacting with Python dataclasses.
Other
171 stars 21 forks source link

YAMLWizard skip_defaults #86

Open Kryan90 opened 1 year ago

Kryan90 commented 1 year ago

Description

I am trying to figure out the "correct" way to use skip_defaults with the YAMLWizard mixin

What I Did

I have found two ways to get it working

  1. By subclassing YAMLWizard

    
    class NoDefaultsWizard(YAMLWizard):
    
    def __init_subclass__(cls, key_transform=None):
        DumpMeta(skip_defaults=True).bind_to(cls)

@dataclass class TestClass(NoDefaultsWizard): a: list[int] = field(default_factory=list) b: list[int] = field(default_factory=list)

c = TestClass(a=[1, 2]) print(c.to_yaml())

2. Binding after the class definition
```python
@dataclass
class TestClass(YAMLWizard):
    a: list[int] = field(default_factory=list)
    b: list[int] = field(default_factory=list)

DumpMeta(skip_defaults=True).bind_to(TestClass)
c = TestClass(a=[1, 2])
print(c.to_yaml())

Are either of these the recommended approach?

I looked at the options here but it seems these only work for JSONSerializable classes of which YAMLWizard is not one

If either of these are preferred, I'd be happy to submit a PR to add their usage to the docs for YAMLWizard.

Thanks for the great library!

adamcunnington-mlg commented 3 months ago

@Kryan90 I'm wondering if you can help as I have a similar question.

I am trying to set json_key_to_field which is a Meta argument but not a DumpMeta argument. I also can't use the Meta subclass because it's not used by the Yaml mixin. How can I do this - is there some similar way I can achieve it within the __init_subclass__ method?

rnag commented 3 days ago

@Kryan90 Apologies for the (long) delay. I am slowly getting back into checking on GitHub issues.

The First approach seems best to me. This is because it skips default __init_subclass__ which assigns key transform of LetterCase.LISP and binds it to the class. With this approach, it is clean, skips any default key transform, and only sets skip_defaults in the DumpMeta. I like this approach, though the Second one is a valid approach as well.

For sure, I would be happy to review a PR to add their usage to the docs for YAMLWizard.

@adamcunnington-mlg I would suggest looking into LoadMeta, which IIRC supports the json_key_to_field argument that you are asking about. Hope this helps!