Creating nested dataclass objects in Python

后端 未结 6 1791
礼貌的吻别
礼貌的吻别 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:39

    from dataclasses import dataclass, asdict
    
    from validated_dc import ValidatedDC
    
    
    @dataclass
    class Foo(ValidatedDC):
        one: int
        two: str
    
    
    @dataclass
    class Bar(ValidatedDC):
        three: str
        foo: Foo
    
    
    data = {'three': 'three', 'foo': {'one': 1, 'two': 'two'}}
    bar = Bar(**data)
    assert bar == Bar(three='three', foo=Foo(one=1, two='two'))
    
    data = {'three': 'three', 'foo': Foo(**{'one': 1, 'two': 'two'})}
    bar = Bar(**data)
    assert bar == Bar(three='three', foo=Foo(one=1, two='two'))
    
    # Use asdict() to work with the dictionary:
    
    bar_dict = asdict(bar)
    assert bar_dict == {'three': 'three', 'foo': {'one': 1, 'two': 'two'}}
    
    foo_dict = asdict(bar.foo)
    assert foo_dict == {'one': 1, 'two': 'two'}
    

    ValidatedDC: https://github.com/EvgeniyBurdin/validated_dc

提交回复
热议问题