Python dataclass from a nested dict

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

    You can use mashumaro for creating dataclass object from a dict according to the scheme. Mixin from this library adds convenient from_dict and to_dict methods to dataclasses:

    from dataclasses import dataclass
    from typing import List
    from mashumaro import DataClassDictMixin
    
    @dataclass
    class Point(DataClassDictMixin):
         x: int
         y: int
    
    @dataclass
    class C(DataClassDictMixin):
         mylist: List[Point]
    
    p = Point(10, 20)
    tmp = {'x': 10, 'y': 20}
    assert p.to_dict() == tmp
    assert Point.from_dict(tmp) == p
    
    c = C([Point(0, 0), Point(10, 4)])
    tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
    assert c.to_dict() == tmp
    assert C.from_dict(tmp) == c
    

提交回复
热议问题