Skip to content

Instantly share code, notes, and snippets.

@balkian
Created March 18, 2015 23:25
Show Gist options
  • Save balkian/1b3cb1d48c75d2172d88 to your computer and use it in GitHub Desktop.
Save balkian/1b3cb1d48c75d2172d88 to your computer and use it in GitHub Desktop.
Python property that mirrors the content of a dictionary. To convenienty add to a subclass of dict and then do: my_object.my_property
class MessageProperty(property):
def __init__(self, path, *args, **kwargs):
property.__init__(self, *args, **kwargs)
self.path = path
def _target(self, dic):
path = self.path
dest = dic
lastkey = path[-1]
for p in path[:-1]:
if p not in dest or not dest[p]:
dest[p] = {}
dest = dest[p]
return dest, lastkey
def __get__(self, container, _type=None):
dest, lastkey = self._target(container)
return dest[lastkey]
def __set__(self, container, value):
dest, lastkey = self._target(container)
dest[lastkey] = value
def __delete__(self, container):
dest, lastkey = self._target(container)
del dest[lastkey]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment