Skip to content

Instantly share code, notes, and snippets.

@rwev
Created August 28, 2018 04:41
Show Gist options
  • Save rwev/1c20cfc6876d5ec799d90f79427b6868 to your computer and use it in GitHub Desktop.
Save rwev/1c20cfc6876d5ec799d90f79427b6868 to your computer and use it in GitHub Desktop.
Implements MemBerDict, a nested dictionary-like Python object offering member attributes for faster access and improved code aesthetic.
"""
MBD.PY: MemBerDict
Implements MemBerDict, a nested dictionary-like object offering member attributes for faster access and improved code aesthetic.
Standard Python dictionaries can be converted to an MBD instance with convertDictToMBD,
enabling streamlined connection to many Python serialization libraries, whose load functions return a Python dictionary.
Similarly, an MBD instance can be converted to a Python dictionary to be fed to a serialization save.
"""
from collections import OrderedDict
class MBD(OrderedDict):
_closed = False
def _close(self):
self._closed = True
for key, val in self.items():
if isinstance(val, MBD):
val._close()
def _open(self):
self._closed = False
def __missing__(self, key):
if self._closed:
raise KeyError
value = self[key] = MBD()
return value
def __getattr__(self, key):
if key.startswith('_'):
raise AttributeError
return self[key]
def __setattr__(self, key, value):
if key.startswith('_'):
self.__dict__[key] = value
return
self[key] = value
def convertDictToMBD(d):
mbd = MBD()
for key, value in d.iteritems():
if isinstance(value, dict):
setattr(mbd, key, convertDictToMBD(value))
else:
setattr(mbd, key, value)
return mbd
def convertMBDtoDict(mbd):
d = {}
for key, value in mbd.iteritems():
if isinstance(value, MBD):
d[key] = convertMBDtoDict(value)
else:
d[key] = value
return d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment