forked from 3b1b/videos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdict_shenanigans.py
67 lines (51 loc) · 1.93 KB
/
dict_shenanigans.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
import inspect
from manimlib.utils.dict_ops import merge_dicts_recursively
def filtered_locals(caller_locals):
result = caller_locals.copy()
ignored_local_args = ["self", "kwargs"]
for arg in ignored_local_args:
result.pop(arg, caller_locals)
return result
def digest_config(obj, kwargs, caller_locals={}):
"""
(Deprecated)
Sets init args and CONFIG values as local variables
The purpose of this function is to ensure that all
configuration of any object is inheritable, able to
be easily passed into instantiation, and is attached
as an attribute of the object.
"""
# Assemble list of CONFIGs from all super classes
classes_in_hierarchy = [obj.__class__]
static_configs = []
while len(classes_in_hierarchy) > 0:
Class = classes_in_hierarchy.pop()
classes_in_hierarchy += Class.__bases__
if hasattr(Class, "CONFIG"):
static_configs.append(Class.CONFIG)
# Order matters a lot here, first dicts have higher priority
caller_locals = filtered_locals(caller_locals)
all_dicts = [kwargs, caller_locals, obj.__dict__]
all_dicts += static_configs
obj.__dict__ = merge_dicts_recursively(*reversed(all_dicts))
def digest_locals(obj, keys=None):
caller_locals = filtered_locals(
inspect.currentframe().f_back.f_locals
)
if keys is None:
keys = list(caller_locals.keys())
for key in keys:
setattr(obj, key, caller_locals[key])
# Occasionally convenient in order to write dict.x instead of more laborious
# (and less in keeping with all other attr accesses) dict["x"]
class DictAsObject(object):
def __init__(self, dict):
self.__dict__ = dict
def get_all_descendent_classes(Class):
awaiting_review = [Class]
result = []
while awaiting_review:
Child = awaiting_review.pop()
awaiting_review += Child.__subclasses__()
result.append(Child)
return result