Python dataclass from a nested dict

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

    undictify is a library which could be of help. Here is a minimal usage example:

    import json
    from dataclasses import dataclass
    from typing import List, NamedTuple, Optional, Any
    
    from undictify import type_checked_constructor
    
    
    @type_checked_constructor(skip=True)
    @dataclass
    class Heart:
        weight_in_kg: float
        pulse_at_rest: int
    
    
    @type_checked_constructor(skip=True)
    @dataclass
    class Human:
        id: int
        name: str
        nick: Optional[str]
        heart: Heart
        friend_ids: List[int]
    
    
    tobias_dict = json.loads('''
        {
            "id": 1,
            "name": "Tobias",
            "heart": {
                "weight_in_kg": 0.31,
                "pulse_at_rest": 52
            },
            "friend_ids": [2, 3, 4, 5]
        }''')
    
    tobias = Human(**tobias_dict)
    

提交回复
热议问题