Python dataclass from a nested dict

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

    Using no additional modules, you can make use of the __post_init__ function to automatically convert the dict values to the correct type. This function is called after __init__.

    from dataclasses import dataclass, asdict
    
    
    @dataclass
    class Bar:
        fee: str
        far: str
    
    @dataclass
    class Foo:
        bar: Bar
    
        def __post_init__(self):
            if isinstance(self.bar, dict):
                self.bar = Bar(**self.bar)
    
    foo = Foo(bar=Bar(fee="La", far="So"))
    
    d= asdict(foo)
    print(d)  # {'bar': {'fee': 'La', 'far': 'So'}}
    o = Foo(**d)
    print(o)  # Foo(bar=Bar(fee='La', far='So'))
    

    This solution has the added benefit of being able to use non-dataclass objects. As long as its str function can be converted back, it's fair game. For example, it can be used to keep str fields as IP4Address internally.

提交回复
热议问题