https://code.activestate.com/recipes/578644-wrist-friendly-dictionary/
class easyaccessdict(dict):
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
super().__setitem__(name,value)
def __missing__(self, name):
super().__setitem__(name, easyaccessdict())
return super().__getitem__(name)
>>> d= easyaccessdict()
>>> d
{}
>>> d.foo.bar= 'a'
>>> d
{'foo':{'bar':'a'}}
>>> d['foo']
{'bar':'a'}
>>> d['foo'].blah= 7
>>> d
{'foo':{'bar':'a', 'blah':7}}
>>> d.a.b.c.e.e.f.g.h= 11
Also I have a use case where would be good to accept the dot syntax in the dict:
>>> from path_dict import PathDict
>>> d = PathDict({})
>>> d['a.b.c.d'] = 2
>>> print(dict(d))
{'a.b.c.d': 2}
This is my current workaround:
>>> from path_dict import PathDict
>>> d = PathDict({})
>>> d[*'a.b.c.d'.split('.')] = 2
>>> print(dict(d))
{'a': {'b': {'c': {'d': 2}}}}
A small change here would fix the issue:
before:
def __getitem__(self, path):
at = self.at(*path) if isinstance(path, tuple) else self.at(path)
if isinstance(at, MultiPathDict):
return at.gather()
res = at.get()
self.at_root()
return res
after:
def __getitem__(self, path):
if isinstance(path, str):
path = path.split('.')
at = self.at(*path) if isinstance(path, tuple) else self.at(path)
if isinstance(at, MultiPathDict):
return at.gather()
res = at.get()
self.at_root()
return res
same goes to __set__
https://code.activestate.com/recipes/578644-wrist-friendly-dictionary/
Also I have a use case where would be good to accept the dot syntax in the dict:
This is my current workaround:
A small change here would fix the issue:
before:
after:
same goes to
__set__