Python dataclass from a nested dict

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

    I'm the author of dacite - the tool that simplifies creation of data classes from dictionaries.

    This library has only one function from_dict - this is a quick example of usage:

    from dataclasses import dataclass
    from dacite import from_dict
    
    @dataclass
    class User:
        name: str
        age: int
        is_active: bool
    
    data = {
        'name': 'john',
        'age': 30,
        'is_active': True,
    }
    
    user = from_dict(data_class=User, data=data)
    
    assert user == User(name='john', age=30, is_active=True)
    

    Moreover dacite supports following features:

    • nested structures
    • (basic) types checking
    • optional fields (i.e. typing.Optional)
    • unions
    • collections
    • values casting and transformation
    • remapping of fields names

    ... and it's well tested - 100% code coverage!

    To install dacite, simply use pip (or pipenv):

    $ pip install dacite
    

提交回复
热议问题