Created
March 18, 2015 23:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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