-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase.py
232 lines (192 loc) · 7.19 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import json
from loguru import logger
import os
class BaseClass:
"""
Base class for providing a serialization and deserialization mechanism.
"""
def __init__(self, **kwargs):
"""
Instantiates the base class with keyword arguments
Args:
kwargs (dict): Keyword arguments
"""
self.kwargs = kwargs
self.__dict__.update(kwargs)
def generate_list_settings(self, list_):
"""
Converts provided list to a normalized list that can be stored as a json object to serialize.
Args:
list_ (List): List to be converted
Returns
Transformed normal list
"""
normal_list = []
for item in list_:
if isinstance(item, BaseClass):
normal_list.append(item.generate_settings())
elif isinstance(item, dict):
normal_list.append(self.generate_kwarg_setting(item))
elif isinstance(item, (tuple, list)):
normal_list.append(self.generate_list_settings(item))
else:
normal_list.append(item)
return normal_list
def generate_kwarg_setting(self, kwargs):
"""
Converts provided keyword arguments to normal kwargs in terms of serialization.
Args:
kwargs (dict): kwargs to be converted.
"""
normal_kwargs = dict()
for kwarg in kwargs:
if isinstance(kwargs[kwarg], BaseClass):
normal_kwargs[kwarg] = kwargs[kwarg].generate_settings()
elif isinstance(kwargs[kwarg], (list, tuple)):
normal_kwargs[kwarg] = self.generate_list_settings(kwargs[kwarg])
elif isinstance(kwargs[kwarg], dict):
normal_kwargs[kwarg] = self.generate_kwarg_setting(kwargs[kwarg])
else:
normal_kwargs[kwarg] = kwargs[kwarg]
return normal_kwargs
def generate_settings(self):
"""
Generates settings for the instance of the BaseClass.
Returns
Settings in dictionary format.
"""
settings = {
"class": self.__class__.__name__,
**self.generate_kwarg_setting({kwarg: self.__dict__[kwarg] for kwarg in self.kwargs}),
}
return settings
def save(self, path):
"""
Saves the generated settings into a JSON file at a specified path.
Args:
path (string): The file path at which the settings have to be saved.
"""
settings = self.generate_settings()
if os.path.dirname(path) != "":
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
json.dump(settings, f, indent=2)
@classmethod
def get_all_subclasses(cls):
"""
Returns all subclasses of the BaseClass.
"""
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(subclass.get_all_subclasses())
return all_subclasses
@staticmethod
def find_class(cls_name):
"""
Searches for a class that matches the given class name.
Args:
cls_name (string): Class name to be matched
"""
for possible_cls in BaseClass.get_all_subclasses():
if possible_cls.__name__ == cls_name:
return possible_cls
return None
@staticmethod
def load_from_list_settings(list_):
"""
Deserializes the list saved settings to instantiate the objects.
Args:
list_ (List): List of saved settings
"""
output_list = []
for item in list_:
if isinstance(item, dict):
output_list.append(BaseClass.load_from_dict(item))
elif isinstance(item, (tuple, list)):
output_list.append(BaseClass.load_from_list_settings(item))
else:
output_list.append(item)
return output_list
@staticmethod
def load_from_dict(dict_):
"""
Deserializes the dictionary saved settings to instantiate the objects.
Args:
dict_ (dict): Dictionary containing saved settings
"""
other_class = BaseClass.find_class(dict_.get("class", None))
if other_class is not None:
return other_class.load_from_settings(dict_)
output_dict = dict()
for key in dict_:
if isinstance(dict_[key], dict):
output_dict[key] = BaseClass.load_from_dict(dict_[key])
elif isinstance(dict_[key], (tuple, list)):
output_dict[key] = BaseClass.load_from_list_settings(dict_[key])
else:
output_dict[key] = dict_[key]
return output_dict
@staticmethod
def load_from_settings(settings):
"""
Deserializes the saved settings to instantiate the object.
Args:
settings (dict): Saved settings
"""
cls = BaseClass.find_class(settings["class"])
if cls is None:
logger.error(f"Could not find class {settings['class']} when loading class.")
return None
kwargs = dict()
for kwarg in settings:
if kwarg == "class":
continue
if isinstance(settings[kwarg], dict):
kwargs[kwarg] = BaseClass.load_from_dict(settings[kwarg])
elif isinstance(settings[kwarg], (tuple, list)):
kwargs[kwarg] = BaseClass.load_from_list_settings(settings[kwarg])
else:
kwargs[kwarg] = settings[kwarg]
return cls(**kwargs)
@classmethod
def _load(cls, path, **kwargs):
"""
Loads the settings from the JSON file at the specified path.
Args:
path (string): The file path from which the settings have to be loaded.
kwargs (dict): Additional keywords arguments
"""
with open(path, "r") as f:
settings = json.load(f)
for kwarg in kwargs:
settings[kwarg] = kwargs[kwarg]
return cls.load_from_settings(settings)
@staticmethod
def load(path, **kwargs):
"""
Loads the settings of the class from the JSON file.
Args:
path (string): The file path from which the class settings have to be loaded.
kwargs (dict): Additional keywords arguments
"""
with open(path, "r") as f:
settings = json.load(f)
cls = BaseClass.find_class(settings["class"])
return cls._load(path, **kwargs)
def __str__(self) -> str:
"""
Returns a string representation of the class object.
"""
return f"{self.__class__.__name__}({self.kwargs})"
def __eq__(self, o: object) -> bool:
"""
Checks whether the provided object is equal to the current object.
Args:
o (object): Object to compare
"""
if not isinstance(o, BaseClass):
return False
other_settings = o.generate_settings()
settings = self.generate_settings()
return other_settings == settings