Python dataclass from a nested dict

后端 未结 10 751
孤街浪徒
孤街浪徒 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:15

    All it takes is a five-liner:

    def dataclass_from_dict(klass, d):
        try:
            fieldtypes = {f.name:f.type for f in dataclasses.fields(klass)}
            return klass(**{f:dataclass_from_dict(fieldtypes[f],d[f]) for f in d})
        except:
            return d # Not a dataclass field
    

    Sample usage:

    from dataclasses import dataclass, asdict
    
    @dataclass
    class Point:
        x: float
        y: float
    
    @dataclass
    class Line:
        a: Point
        b: Point
    
    line = Line(Point(1,2), Point(3,4))
    assert line == dataclass_from_dict(Line, asdict(line))
    

    Full code, including to/from json, here at gist: https://gist.github.com/gatopeich/1efd3e1e4269e1e98fae9983bb914f22

提交回复
热议问题