dataclass-wizard
dataclass-wizard copied to clipboard
Question: Is it possible to handle kwargs with `YAMLWizard`?
- Dataclass Wizard version: 0.22.3
- Python version: 3.12.2
- Operating System: macOS Sonoma 14.4.1
Description
How can I store kwargs not explicitly called out as an attribute in the kwargs attribute using YAMLWizard
?
What I Did
Without YAMLWizard
, I can accomplish what I want like so:
from dataclasses import dataclass, field
from inspect import signature
from typing import Any
@dataclass
class Data:
x: str
y: str
kwargs: Any = field(default_factory=dict)
@classmethod
def from_kwargs(cls, **kwargs):
# Fetch constructors signature
cls_fields = {fld for fld in signature(cls).parameters}
# Split kwargs into native ones and new ones
native_args, new_args = {}, {}
for name, value in kwargs.items():
if name in cls_fields:
native_args[name] = value
else:
new_args[name] = value
# Return new class storing new kwargs into kwargs attribute
return cls(**native_args, kwargs=new_args)
params = dict(x='time', y='temp', linecolor='blue', linewidth=10)
data = Data.from_kwargs(**params)
data
Data(x='time', y='temp', kwargs={'linecolor': 'blue', 'linewidth': 10})
I can't figure out how (assuming it's possible) to use YAMLWizard
to do the same thing:
from dataclass_wizard import YAMLWizard
@dataclass
class Class1a(YAMLWizard):
data: list[Data] = field(default_factory=list)
cls1a = Class1a.from_yaml("""
data:
- x: x1
y: y1
linecolor: blue
- x: x2
y: y2
linecolor: red
linewidth: 2
""")
cls1a
Class1(data=[Data(x='x1', y='y1', kwargs={}), Data(x='x2', y='y2', kwargs={})])
I expected the result above because I'm not using Data.from_kwargs()
to create the object. I also tried adding this instead data: list[Data] = field(default_factory=list[Data.from_kwargs])
, but that produced the same result.
Is it possible to make YAMLWizard
use the classmethod
.from_kwargs()
?