Created
December 4, 2020 22:01
-
-
Save nockstarr/7f6f285f15af849c0fb27a2f72928d3e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from pprint import pprint | |
from typing import List, Dict | |
class DataBase: | |
""" useful base functions for dataclasses that can convert a dataclass to_dict recursively """ | |
def _list_of_dc(self, data_classes: list or set) -> List[dict]: | |
""" Convert list of classes with to_dict() atter to list of dict""" | |
return [item.to_dict() if hasattr(item, "to_dict") else item for item in data_classes] | |
# def to_dict(self): | |
# """ Short version cant support list or set """ | |
# return {k: (v.to_dict() if hasattr(v, "to_dict") else v) for k, v in self.__dict__.items()} | |
def _to_dict(self, data: dict) -> dict: | |
cls_as_dict = {} | |
for k, v in data.items(): | |
if hasattr(v, "to_dict"): | |
cls_as_dict[k] = v.to_dict() | |
elif isinstance(v, list) or isinstance(v, set): | |
cls_as_dict[k] = self._list_of_dc(v) | |
elif isinstance(v, dict): | |
cls_as_dict[k] = self._to_dict(v) | |
else: | |
cls_as_dict[k] = v | |
return cls_as_dict | |
def to_dict(self) -> dict: | |
""" dataclass to dict recursively""" | |
return self._to_dict(self.__dict__) | |
@dataclass | |
class Person(DataBase): | |
name: str | |
lastname: str | |
@dataclass | |
class Test(DataBase): | |
p: Person | |
t: str | |
list_names: List[Person] | |
dict_names: Dict[str, Person] | |
p1 = Person(name="p1", lastname="p1 lastname") | |
p2 = Person(name="p2", lastname="p2 lastname") | |
p3 = Person(name="p3", lastname="p3 lastname") | |
t = Test(p=p1, t="test", list_names=[p1, p2, p3, "lool"], dict_names={"p1": p1, "p2": p2, "p3": p3}) | |
print(t) | |
pprint(t.to_dict()) | |
""" | |
# print(t): | |
Test(p=Person(name='p1', lastname='p1 lastname'), t='test', list_names=[Person(name='p1', lastname='p1 lastname'), Person(name='p2', lastname='p2 lastname'), Person(name='p3', lastname='p3 lastname'), 'lool']) | |
# pprint(t.to_dict()): | |
{ | |
'dict_names': { | |
'p1': { | |
'lastname': 'p1 lastname', | |
'name': 'p1' | |
}, | |
'p2': { | |
'lastname': 'p2 lastname', | |
'name': 'p2' | |
}, | |
'p3': { | |
'lastname': 'p3 lastname', | |
'name': 'p3' | |
} | |
}, | |
'list_names': [ | |
{ | |
'lastname': 'p1 lastname', | |
'name': 'p1' | |
}, | |
{ | |
'lastname': 'p2 lastname', | |
'name': 'p2' | |
}, | |
{ | |
'lastname': 'p3 lastname', | |
'name': 'p3' | |
}, | |
'lool' | |
], | |
'p': { | |
'lastname': 'p1 lastname', | |
'name': 'p1' | |
}, | |
't': 'test' | |
} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment