-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathdotmap.py
More file actions
executable file
·399 lines (359 loc) · 12.9 KB
/
Copy pathdotmap.py
File metadata and controls
executable file
·399 lines (359 loc) · 12.9 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
from collections import OrderedDict
from collections.abc import MutableMapping, Iterable
from json import dumps
from pprint import pprint
from sys import version_info
from inspect import ismethod
# for debugging
def here(item=None):
out = 'here'
if item != None:
out += '({})'.format(item)
print(out)
__all__ = ['DotMap', 'StaticDotMap']
class DotMap(MutableMapping, OrderedDict):
def __init__(self, *args, **kwargs):
self._map = OrderedDict()
default_dynamic = getattr(type(self), '_dynamic', True)
self._dynamic = kwargs.pop('_dynamic', default_dynamic)
if default_dynamic is False and self._dynamic:
raise ValueError(f'can not set `_dynamic={self._dynamic!r}` for {self.__class__.__name__}')
self._default_factory = kwargs.pop('_default_factory', None)
if self._default_factory is not None and not callable(self._default_factory):
raise TypeError('_default_factory must be callable')
if self._default_factory is not None and not self._dynamic:
raise ValueError('cannot provide _default_factory when _dynamic is False')
self._prevent_method_masking = kwargs.pop('_prevent_method_masking', False)
_key_convert_hook = kwargs.pop('_key_convert_hook', None)
trackedIDs = kwargs.pop('_trackedIDs', {})
if args:
d = args[0]
# for recursive assignment handling
trackedIDs[id(d)] = self
src = []
if isinstance(d, MutableMapping):
src = self.__call_items(d)
elif isinstance(d, Iterable):
src = d
child_kwargs = {
'_dynamic': self._dynamic,
'_default_factory': self._default_factory,
'_prevent_method_masking': self._prevent_method_masking,
'_key_convert_hook': _key_convert_hook,
'_trackedIDs': trackedIDs
}
for k,v in src:
if self._prevent_method_masking and k in reserved_keys:
raise KeyError('"{}" is reserved'.format(k))
if _key_convert_hook:
k = _key_convert_hook(k)
if isinstance(v, dict):
idv = id(v)
if idv in trackedIDs:
v = trackedIDs[idv]
else:
trackedIDs[idv] = v
v = self.__class__(v, **child_kwargs)
if type(v) is list:
l = []
for i in v:
n = i
if isinstance(i, dict):
idi = id(i)
if idi in trackedIDs:
n = trackedIDs[idi]
else:
trackedIDs[idi] = i
n = self.__class__(i, **child_kwargs)
l.append(n)
v = l
self._map[k] = v
if kwargs:
for k,v in self.__call_items(kwargs):
if self._prevent_method_masking and k in reserved_keys:
raise KeyError('"{}" is reserved'.format(k))
if _key_convert_hook:
k = _key_convert_hook(k)
self._map[k] = v
def __call_items(self, obj):
if hasattr(obj, 'iteritems') and ismethod(getattr(obj, 'iteritems')):
return obj.iteritems()
else:
return obj.items()
def items(self):
return self.iteritems()
def iteritems(self):
return self.__call_items(self._map)
def __iter__(self):
return self._map.__iter__()
def next(self):
return self._map.next()
def __setitem__(self, k, v):
self._map[k] = v
def __getitem__(self, k):
if k not in self._map:
if self._dynamic and k != '_ipython_canary_method_should_not_exist_':
if self._default_factory is not None:
self[k] = self._default_factory()
else:
# automatically extend to new DotMap
self[k] = self.__class__()
return self._map[k]
def __setattr__(self, k, v):
if k in {
'_map', '_dynamic', '_default_factory',
'_ipython_canary_method_should_not_exist_',
'_prevent_method_masking'
}:
super(DotMap, self).__setattr__(k,v)
elif self._prevent_method_masking and k in reserved_keys:
raise KeyError('"{}" is reserved'.format(k))
else:
self[k] = v
def __getattr__(self, k):
if k.startswith('__') and k.endswith('__'):
raise AttributeError(k)
if k in {
'_map', '_dynamic', '_default_factory',
'_ipython_canary_method_should_not_exist_'
}:
return super(DotMap, self).__getattr__(k)
try:
v = super(self.__class__, self).__getattribute__(k)
return v
except AttributeError:
pass
try:
return self[k]
except KeyError:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{k}'") from None
def __delattr__(self, key):
return self._map.__delitem__(key)
def __contains__(self, k):
return self._map.__contains__(k)
def __add__(self, other):
if self.empty():
return other
else:
self_type = type(self).__name__
other_type = type(other).__name__
msg = "unsupported operand type(s) for +: '{}' and '{}'"
raise TypeError(msg.format(self_type, other_type))
def __str__(self, seen = None):
items = []
seen = {id(self)} if seen is None else seen
for k,v in self.__call_items(self._map):
# circular assignment case
if isinstance(v, self.__class__):
if id(v) in seen:
items.append('{0}={1}(...)'.format(k, self.__class__.__name__))
else:
seen.add(id(v))
items.append('{0}={1}'.format(k, v.__str__(seen)))
else:
items.append('{0}={1}'.format(k, repr(v)))
joined = ', '.join(items)
out = '{0}({1})'.format(self.__class__.__name__, joined)
return out
def __repr__(self):
return str(self)
def toDict(self, seen = None):
if seen is None:
seen = {}
d = {}
seen[id(self)] = d
for k,v in self.items():
if issubclass(type(v), DotMap):
idv = id(v)
if idv in seen:
v = seen[idv]
else:
v = v.toDict(seen = seen)
elif type(v) in (list, tuple):
l = []
for i in v:
n = i
if issubclass(type(i), DotMap):
idv = id(n)
if idv in seen:
n = seen[idv]
else:
n = i.toDict(seen = seen)
l.append(n)
if type(v) is tuple:
v = tuple(l)
else:
v = l
d[k] = v
return d
def pprint(self, pformat='dict'):
if pformat == 'json':
print(dumps(self.toDict(), indent=4, sort_keys=True))
else:
pprint(self.toDict())
def empty(self):
return (not any(self))
# proper dict subclassing
def values(self):
return self._map.values()
# ipython support
def __dir__(self):
return self.keys()
@classmethod
def parseOther(self, other):
if issubclass(type(other), DotMap):
return other._map
else:
return other
def __cmp__(self, other):
other = DotMap.parseOther(other)
return self._map.__cmp__(other)
def __eq__(self, other):
other = DotMap.parseOther(other)
if not isinstance(other, dict):
return False
return self._map.__eq__(other)
def __ge__(self, other):
other = DotMap.parseOther(other)
return self._map.__ge__(other)
def __gt__(self, other):
other = DotMap.parseOther(other)
return self._map.__gt__(other)
def __le__(self, other):
other = DotMap.parseOther(other)
return self._map.__le__(other)
def __lt__(self, other):
other = DotMap.parseOther(other)
return self._map.__lt__(other)
def __ne__(self, other):
other = DotMap.parseOther(other)
return self._map.__ne__(other)
def __delitem__(self, key):
return self._map.__delitem__(key)
def __len__(self):
return self._map.__len__()
def clear(self):
self._map.clear()
def copy(self):
return self.__class__(
self,
_dynamic=self._dynamic,
_default_factory=self._default_factory,
_prevent_method_masking=self._prevent_method_masking,
)
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo=None):
return self.copy()
def get(self, key, default=None):
return self._map.get(key, default)
def has_key(self, key):
return key in self._map
def iterkeys(self):
return self._map.iterkeys()
def itervalues(self):
return self._map.itervalues()
def keys(self):
return self._map.keys()
def pop(self, key, default=None):
return self._map.pop(key, default)
def popitem(self):
return self._map.popitem()
def setdefault(self, key, default=None):
return self._map.setdefault(key, default)
def update(self, *args, **kwargs):
if len(args) != 0:
self._map.update(*args)
self._map.update(kwargs)
def viewitems(self):
return self._map.viewitems()
def viewkeys(self):
return self._map.viewkeys()
def viewvalues(self):
return self._map.viewvalues()
@classmethod
def fromkeys(cls, seq, value=None):
d = cls()
d._map = OrderedDict.fromkeys(seq, value)
return d
def __getstate__(self): return self.__dict__
def __setstate__(self, d):
self.__dict__.update(d)
if '_default_factory' not in self.__dict__:
self._default_factory = None
# bannerStr
def _getListStr(self,items):
out = '['
mid = ''
for i in items:
mid += ' {}\n'.format(i)
if mid != '':
mid = '\n' + mid
out += mid
out += ']'
return out
def _getValueStr(self,k,v):
outV = v
multiLine = len(str(v).split('\n')) > 1
if multiLine:
# push to next line
outV = '\n' + v
if type(v) is list:
outV = self._getListStr(v)
out = '{} {}'.format(k,outV)
return out
def _getSubMapDotList(self, pre, name, subMap):
outList = []
if pre == '':
pre = name
else:
pre = '{}.{}'.format(pre,name)
def stamp(pre,k,v):
valStr = self._getValueStr(k,v)
return '{}.{}'.format(pre, valStr)
for k,v in subMap.items():
if isinstance(v,DotMap) and v != DotMap():
subList = self._getSubMapDotList(pre,k,v)
outList.extend(subList)
else:
outList.append(stamp(pre,k,v))
return outList
def _getSubMapStr(self, name, subMap):
outList = ['== {} =='.format(name)]
for k,v in subMap.items():
if isinstance(v, self.__class__) and v != self.__class__():
# break down to dots
subList = self._getSubMapDotList('',k,v)
# add the divit
# subList = ['> {}'.format(i) for i in subList]
outList.extend(subList)
else:
out = self._getValueStr(k,v)
# out = '> {}'.format(out)
out = '{}'.format(out)
outList.append(out)
finalOut = '\n'.join(outList)
return finalOut
def bannerStr(self):
lines = []
previous = None
for k,v in self.items():
if previous == self.__class__.__name__:
lines.append('-')
out = ''
if isinstance(v, self.__class__):
name = k
subMap = v
out = self._getSubMapStr(name,subMap)
lines.append(out)
previous = self.__class__.__name__
else:
out = self._getValueStr(k,v)
lines.append(out)
previous = 'other'
lines.append('--')
s = '\n'.join(lines)
return s
class StaticDotMap(DotMap):
_dynamic = False
reserved_keys = {i for i in dir(DotMap) if not i.startswith('__') and not i.endswith('__')}