Python dataclass from a nested dict

后端 未结 10 749
孤街浪徒
孤街浪徒 2020-12-22 23:38

The standard library in 3.7 can recursively convert a dataclass into a dict (example from the docs):

from dataclasses import dataclass, asdict
from typing im         


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 00:07

    I would like to suggest using the Composite Pattern to solve this, the main advantage is that you could continue adding classes to this pattern and have them behave the same way.

    from dataclasses import dataclass
    from typing import List
    
    
    @dataclass
    class CompositeDict:
        def as_dict(self):
            retval = dict()
            for key, value in self.__dict__.items():
                if key in self.__dataclass_fields__.keys():
                    if type(value) is list:
                        retval[key] = [item.as_dict() for item in value]
                    else:
                        retval[key] = value
            return retval
    
    @dataclass
    class Point(CompositeDict):
        x: int
        y: int
    
    
    @dataclass
    class C(CompositeDict):
        mylist: List[Point]
    
    
    c = C([Point(0, 0), Point(10, 4)])
    tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
    assert c.as_dict() == tmp
    

    as a side note, you could employ a factory pattern within the CompositeDict class that would handle other cases like nested dicts, tuples and such, which would save much boilerplate.

提交回复
热议问题