-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasydict.py
executable file
·38 lines (26 loc) · 991 Bytes
/
easydict.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
#!/usr/bin/python
import collections
# auto-vivify nested dicts of any depth
class autodict(collections.defaultdict):
def __init__(self, *other, **kw):
collections.defaultdict.__init__(self, type(self), *other, **kw)
def __add__(self, other):
return other
__repr__ = dict.__repr__
# read-write attribute access to dict keys
class _easydict(autodict):
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, val):
self[name] = val
# recursively convert/upgrade a dict to some kind of fancy dict
def dconvert(dtype, d):
if isinstance(d, dict):
return dtype( dconvert(dtype, x) for x in d.items() )
if isinstance(d, (tuple, list)):
return type(d)( dconvert(dtype, x) for x in d )
return d
# wrapper to convert objects as necessary recursively to easydict
def easydict(_d=None, **_kw):
d = _kw if _d is None else dict(_d, **_kw) if _kw else _d
return dconvert(_easydict, d)