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 import List
@dataclass
class Point:
x: int
y: int
@dataclass
class C:
mylist: List[Point]
p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}
c = C([Point(0, 0), Point(10, 4)])
tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
assert asdict(c) == tmp
I am looking for a way to turn a dict back into a dataclass when there is nesting. Something like C(**tmp)
only works if the fields of the data class are simple types and not themselves dataclasses. I am familiar with [jsonpickle][1], which however comes with a prominent security warning.
EDIT:
Answers have suggested the following libraries:
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:
... and it's well tested - 100% code coverage!
To install dacite, simply use pip (or pipenv):
$ pip install dacite