fork(1) download
  1. class DotDictionary(dict):
  2.  
  3. def __init__(self, init_value=None):
  4.  
  5. if not init_value:
  6. init_value = {}
  7.  
  8. super(DotDictionary, self).__init__()
  9. if not isinstance(init_value, dict):
  10. raise TypeError('Expected dict, got {}'.format(type(init_value)))
  11.  
  12. self._dict_to_self(init_value)
  13.  
  14. def __getattr__(self, name):
  15. return self[name]
  16.  
  17. def __setattr__(self, name, val):
  18. if isinstance(val, dict):
  19. val = DotDictionary(val)
  20. self[name] = val
  21.  
  22. def __setitem__(self, name, val):
  23. if isinstance(val, dict):
  24. val = DotDictionary(val)
  25.  
  26. super(DotDictionary, self).__setitem__(name, val)
  27.  
  28. def __delattr__(self, name):
  29. del self[name]
  30.  
  31. def __getstate__(self):
  32. return self
  33.  
  34. def __setstate__(self, state):
  35. self = state
  36.  
  37. def __repr__(self):
  38. return super(DotDictionary, self).__repr__()
  39.  
  40. def _dict_to_self(self, dct):
  41. for key, value in dct.items():
  42. if isinstance(value, (tuple, list)):
  43. for i, _ in enumerate(value):
  44. if isinstance(value[i], dict):
  45. value[i] = DotDictionary(value[i])
  46. self[key] = value
  47.  
  48.  
  49.  
  50. d = {'a': 0,
  51. 'b': {'aa': 1, 'bb': {'aaa': 2, 'bbb': 3, 'ccc': {'aaaa': 4}}},
  52. 'c': [5, {'aaaaa': 6, 'bbbbb': 7, 'ccccc': [{'aaaaaa': 8}]}]}
  53.  
  54. dd = DotDictionary(d)
  55. dd['dict'] = {'hey': 'hey'}
  56. dd.dict.hello = {'hello': 123}
  57.  
  58. print(dd.a)
  59. print(dd.b.aa)
  60. print(dd.c[1].aaaaa)
  61. print(dd.c[1].ccccc[0].aaaaaa)
  62. print(dd.dict.hey)
  63. print(dd.dict.hello.hello)
  64.  
Success #stdin #stdout 0.02s 9984KB
stdin
Standard input is empty
stdout
0
1
6
8
hey
123