Creating nested dataclass objects in Python

后端 未结 6 1777
礼貌的吻别
礼貌的吻别 2020-12-09 10:10

I have a dataclass object that has nested dataclass objects in it. However, when I create the main object, the nested objects turn into a dictionary:

@datacl         


        
6条回答
  •  遥遥无期
    2020-12-09 10:53

    You can try dacite module. This package simplifies creation of data classes from dictionaries - it also supports nested structures.

    Example:

    from dataclasses import dataclass
    from dacite import from_dict
    
    @dataclass
    class A:
        x: str
        y: int
    
    @dataclass
    class B:
        a: A
    
    data = {
        'a': {
            'x': 'test',
            'y': 1,
        }
    }
    
    result = from_dict(data_class=B, data=data)
    
    assert result == B(a=A(x='test', y=1))
    

    To install dacite, simply use pip:

    $ pip install dacite
    

提交回复
热议问题