Last active
December 29, 2021 00:02
-
-
Save Spirit-act/49af1b4036fcb325ad1ead06da61c514 to your computer and use it in GitHub Desktop.
python recursive base class which helps displaying objects as string with the help of __repr__ an repr()
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
# this is a BaseModel which implements the __repr__ method to recursivly convert objects to string | |
from json import dumps, loads | |
class Model: | |
def __repr__(self) -> str: | |
output: dict = {} | |
# name must be defined afterwards because of typing | |
output["name"] = self.__class__.__name__ | |
# loop through all params of the object | |
for key, value in self.__dict__.items(): | |
# check if its a list | |
if isinstance(value, list): | |
# if its a list loop over every object | |
# if the object is from type Model and therefore implements the same __repr__ method | |
# so the __repr__ method will be called | |
# we nee the loads function to get a valid dict and also an usefull string | |
# otherwise it just recreats the list | |
value = [loads(repr(x)) if isinstance(x, Model) else x for x in value] | |
# if it the value is not a list, check if it is an instance of Model | |
elif isinstance(value, Model): | |
# if value is an instance of Model call the __repr__ method | |
value = loads(repr(value)) | |
# add another entry with the key and the maybe reformated value | |
output[key] = value | |
# return the dict as json str with utf-8 chars | |
return dumps(output, ensure_ascii=False) |
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
# the same as the above but not shorted | |
from json import dumps, loads | |
class Model: | |
def __repr__(self): | |
output: dict = {} | |
output["name"] = self.__class__.__name__ | |
for key, value in self.__dict__.items(): | |
if isinstance(value, list): | |
y: list = [] | |
for x in value: | |
if isinstance(x, Model): | |
y.append(loads(x))) | |
else: | |
y.append(x) | |
value = y | |
elif isinstance(value, Model): | |
value = loads(repr(value)) | |
output[key] = value | |
return dumps(output, ensure_ascii=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment