-
Notifications
You must be signed in to change notification settings - Fork 5
/
dictclass.py
372 lines (284 loc) · 11.6 KB
/
dictclass.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import inspect
from copy import copy
from typing import Any, Callable, Dict, Iterable, List, Tuple, Type, TypeVar, cast
from dynamo_query.dictclasses.decorators import KeyComputer, KeySanitizer
__all__ = ("DictClass",)
_R = TypeVar("_R", bound="DictClass")
class DictClass(dict):
"""
Dict-based dataclass.
Examples:
```python
class UserRecord(DictClass):
# required fields
name: str
# optional fields
company: str = "Amazon"
age: Optional[int] = None
def __post_init__(self):
# do any post-init operations here
self.age = self.age or 35
# add extra computed field
@DictClass.compute_key("min_age")
def _compute_min_age(self) -> int:
return 18
# sanitize value on set
@DictClass.sanitize_key("age")
def _sanitize_key_age(self, value: int) -> int:
return max(self.age, 18)
record = UserRecord(name="Jon")
record["age"] = 30
record.age = 30
record.update({"age": 30})
dict(record) # {"name": "Jon", "company": "Amazon", "age": 30, "min_age": 18}
```
"""
# Marker for optional fields with no initial value, set to None if needed
NOT_SET: Any = object()
# KeyError is raised if unknown key provided
RAISE_ON_UNKNOWN_KEY: bool = False
_initialized_classes: List[int] = []
_local_members_cache: Dict[int, Dict[str, Any]] = {}
_local_members: Dict[str, Any] = {}
_sanitizers: Dict[str, List[Callable[..., Any]]] = {}
_computers: Dict[str, Callable[[Any], Any]] = {}
_allowed_types: Dict[str, Tuple[Any, ...]] = {}
_required_field_names: List[str] = []
_field_names: List[str] = []
def __new__(cls: Type[_R], *_args: Dict[str, Any], **_kwargs: Any) -> _R:
instance = super().__new__(cls)
cls._initalize_class()
# instance.__init__(*args, **kwargs)
return cast(_R, instance)
@classmethod
def _initalize_class(cls) -> None:
if id(cls) in cls._initialized_classes:
return
cls._local_members = cls._get_local_members()
cls._sanitizers = cls._get_sanitizers()
cls._computers = cls._get_computers()
cls._allowed_types = cls._get_allowed_types()
cls._initialized_classes.append(id(cls))
cls._required_field_names = cls._get_required_field_names()
cls._field_names = cls._get_field_names()
def __init__(self, *args: Dict[str, Any], **kwargs: Any) -> None:
super().__init__()
self._init_data(*args, kwargs)
self.__post_init__()
def __post_init__(self) -> None:
"""
Override this method for post-init operations
"""
@classmethod
def _get_sanitizers(cls) -> Dict[str, List[Callable[..., Any]]]:
result: Dict[str, List[Callable[..., Any]]] = {}
for member in cls._local_members.values():
if not inspect.isfunction(member):
continue
sanitizer = getattr(member, "KeySanitizer", None)
if not sanitizer:
continue
if sanitizer.key not in result:
result[sanitizer.key] = []
result[sanitizer.key].append(member)
return result
@classmethod
def _get_computers(cls) -> Dict[str, Callable[[Any], Any]]:
result: Dict[str, Callable[[Any], Any]] = {}
for member in cls._local_members.values():
if not inspect.isfunction(member):
continue
computer = getattr(member, "KeyComputer", None)
if not computer:
continue
result[computer.key] = member
return result
@staticmethod
def sanitize_key(key: str) -> KeySanitizer:
return KeySanitizer(key)
@staticmethod
def compute_key(key: str) -> KeyComputer:
return KeyComputer(key)
@classmethod
def _get_allowed_types(cls) -> Dict[str, Tuple[Any, ...]]:
result: Dict[str, Tuple[Any, ...]] = {}
annotations = cls._local_members.get("__annotations__", {})
for key, annotation in annotations.items():
annotation_str = str(annotation)
if not annotation_str.startswith("typing.") and inspect.isclass(annotation):
result[key] = (annotation,)
continue
child_types: Tuple[Any, ...] = tuple()
if hasattr(annotation, "__args__"):
child_types = tuple(i for i in annotation.__args__ if inspect.isclass(i))
result[key] = tuple()
if annotation_str.startswith("typing.Dict"):
result[key] = (dict,)
if annotation_str.startswith("typing.List"):
result[key] = (list,)
if annotation_str.startswith("typing.Set"):
result[key] = (set,)
if annotation_str.startswith("typing.Union"):
result[key] = child_types
return result
@classmethod
def _get_local_members(cls) -> Dict[str, Any]:
base_field_names = {i[0] for i in inspect.getmembers(DictClass)}
result: Dict[str, Any] = {
"__annotations__": {},
}
for key, value in inspect.getmembers(cls):
if key == "__annotations__":
result["__annotations__"].update(value)
continue
if key in base_field_names:
continue
result[key] = value
base_classes = cls._get_base_classes(cls.__bases__)
base_classes.reverse()
for base_class in base_classes:
for key, value in inspect.getmembers(base_class):
if key == "__annotations__":
result["__annotations__"].update(value)
continue
if key in base_field_names or key in result:
continue
return result
@classmethod
def _get_base_classes(cls, base_classes: Iterable[Any]) -> List[Any]:
result: List[Type[DictClass]] = []
for base_class in base_classes:
if base_class is DictClass:
continue
if not issubclass(base_class, DictClass):
continue
result.append(base_class)
result.extend(cls._get_base_classes(base_class.__bases__))
return result
@classmethod
def _get_required_field_names(cls) -> List[str]:
result = []
for key in cls._allowed_types:
if key in cls._local_members:
continue
if key.startswith("_") or key.upper() == key:
continue
result.append(key)
return result
@classmethod
def _get_field_names(cls) -> List[str]:
result = []
for key in cls._allowed_types:
if key in cls._local_members:
continue
if key.startswith("_") or key.upper() == key:
continue
result.append(key)
for key, value in cls._local_members.items():
if key.startswith("_") or key.upper() == key:
continue
if inspect.isfunction(value) or inspect.ismethod(value) or isinstance(value, property):
continue
result.append(key)
return result
def _init_data(self, *mappings: Dict[str, Any]) -> None:
for key, member in self._local_members.items():
if key not in self._field_names:
continue
super().__setitem__(key, copy(member))
for mapping in mappings:
for key, value in mapping.items():
if key in self._computers:
continue
field_name_exists = key in self._field_names
if not field_name_exists and self.RAISE_ON_UNKNOWN_KEY:
raise KeyError(
f"{self._class_name}.{key} does not exist, got value {repr(value)}."
)
if field_name_exists:
super().__setitem__(key, value)
for key in self._field_names:
super().__setitem__(key, self._sanitize_key(key, self.get(key, self.NOT_SET)))
for key, value in list(self.items()):
if value is self.NOT_SET:
del self[key]
for key in self._required_field_names:
if key not in self:
raise ValueError(f"{self._class_name}.{key} must be set: {self}")
self._update_computed()
@property
def _class_name(self) -> str:
return self.__class__.__name__
def _set_item(
self, key: str, value: Any, is_initial: bool, sanitize_kwargs: Dict[str, Any]
) -> None:
sanitized_value = self._sanitize_key(key, value, **sanitize_kwargs)
if not is_initial:
if sanitized_value is self.NOT_SET:
if key in self:
del self[key]
self._update_computed()
return
super().__setitem__(key, sanitized_value)
if not is_initial:
self._update_computed()
def _update_computed(self) -> None:
for key, computer in self._computers.items():
value = computer(self)
if value is self.NOT_SET:
if key in self:
del self[key]
else:
super().__setitem__(key, value)
def __setitem__(self, key: str, value: Any) -> None:
if key in self._computers:
return
if key not in self._field_names:
raise KeyError(f"Key {self._class_name}.{key} is missing in class attributes")
self._set_item(key, value, is_initial=False, sanitize_kwargs={})
def __setattr__(self, name: str, value: Any) -> None:
if name in self._computers:
raise KeyError(f"Key {self._class_name}.{name} is computed and cannot be set directly")
if name not in self._field_names:
raise KeyError(f"Key {self._class_name}.{name} is missing in class attributes")
self._set_item(name, value, is_initial=False, sanitize_kwargs={})
def __getattribute__(self, name: str) -> Any:
if name.startswith("_"):
return super().__getattribute__(name)
if name not in self._field_names:
return super().__getattribute__(name)
return self.get(name, self.NOT_SET)
def __str__(self) -> str:
return f"{self._class_name}({dict(self)})"
def _sanitize_key(self, key: str, value: Any, **kwargs: Any) -> Any:
"""
Sanitize value before putting it to dict.
Calls `sanitize_key_{key}` method if it is defined
Arguments:
key -- Dictionary key
value -- Raw value
Returns:
A sanitized value
"""
for sanitizer in self._sanitizers.get(key, []):
value = sanitizer(self, value, **kwargs)
return value
def sanitize(self, **kwargs: Any) -> None:
"""
Sanitize all set fields.
Arguments:
kwargs -- Arguments for sanitize_key_{key}
"""
for key in self._sanitizers:
value = self.get(key, self.NOT_SET)
self._set_item(key, value, is_initial=False, sanitize_kwargs=kwargs)
def update(self, *args: Dict[str, Any], **kwargs: Any) -> None: # type: ignore
"""
Override of original `dict.update` method to apply `_set_item` rules.
"""
mappings = [*args, kwargs]
for mapping in mappings:
for key, value in mapping.items():
if key not in self._field_names:
continue
self._set_item(key, value, is_initial=False, sanitize_kwargs={})