I'd like to create a dict to a dataclass which contains as a List of dataclass as attribute
Here is an example of what I'd like to achieve:
from typing import List
from dataclasses import dataclass
@dataclass
class level2:
key21: int
key22: int
@nested_dataclass
class level1:
key1: int
key2: List[level2]
data = {
'key1': value1,
'key2': [{
'key21': value21,
'key22': value22,
}]
}
my_object = level1(**data)
print(my_object.key2[0].key21) #should print value21
Closest decorator I found was this one, but it does not work with Lists of dataclass: Creating nested dataclass objects in Python
def is_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
_FIELDS = '__dataclass_fields__'
return hasattr(obj, _FIELDS)
def nested_dataclass(*args, **kwargs):
def wrapper(cls):
cls = dataclass(cls, **kwargs)
original_init = cls.__init__
def __init__(self, *args, **kwargs):
for name, value in kwargs.items():
field_type = cls.__annotations__.get(name, None)
if is_dataclass(field_type) and isinstance(value, dict):
new_obj = field_type(**value)
kwargs[name] = new_obj
original_init(self, *args, **kwargs)
cls.__init__ = __init__
return cls
return wrapper(args[0]) if args else wrapper
How would you modify this decorator or create one that would do the job? (I've got zero experience in building decorator)
Any comment/code is very much appreciated. Thank you