konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.72k stars 107 forks source link

how to serialize a List? #130

Closed jbcpollak closed 3 years ago

jbcpollak commented 3 years ago

can dacite serialize a list? we tried to serialize this:

@dataclass
class FooList(List[FooDataclass]):

but we just get an empty list.

konradhalas commented 3 years ago

hi @jbcpollak - I don't think that you could create dataclass with List[FooDataclass] as a base type.

dacite supports List, here you have simple example:

@dataclass
class A:
    x: str
    y: int

@dataclass
class B:
    a_list: List[A]

data = {
    'a_list': [
        {
            'x': 'test1',
            'y': 1,
        },
        {
            'x': 'test2',
            'y': 2,
        }
    ],
}

result = from_dict(data_class=B, data=data)

assert result == B(a_list=[A(x='test1', y=1), A(x='test2', y=2)])