Last active
October 4, 2018 12:13
-
-
Save arkanister/1bc0fa91ba028e5ebc1442323acfa68f to your computer and use it in GitHub Desktop.
This file contains 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
# coding: utf-8 | |
""" | |
What if I wanna handle a python dict as a object? | |
This object provides the ability to a dict behave as a python object. | |
Usage: | |
>>> a = ObjectDict({'foo': 'bar', 'bar': {'foo': [{'bar': 'foo'}]}}) | |
>>> a.foo | |
>>> 'bar' | |
>>> | |
>>> a.bar | |
>>> {'foo': [{'bar': 'foo'}]} | |
>>> | |
>>> a.bar.foo | |
>>> [{'bar': 'foo'}] | |
>>> | |
>>> a.bar.foo[0].bar | |
>>> 'foo' | |
""" | |
class ObjectDict(dict): | |
""" | |
Gives a simple dict an object behavior. | |
""" | |
def _get_value_from_key(self, item): | |
""" | |
Get a value from a key into dict. | |
""" | |
try: | |
value = self[item] | |
# Nested dict must apply the same behavior | |
# than parent dict | |
if isinstance(value, dict): | |
value = ObjectDict(value) | |
# Grant the ability to apply the object behavior | |
# to dictionaries inside lists. | |
elif isinstance(value, (tuple, list)): | |
value = [ObjectDict(v) if isinstance(v, dict) else v for v in value] | |
return value | |
except KeyError: | |
raise AttributeError('type object \'{name}\' has no attribute {attr}'.format( | |
name=self.__class__.__name__, | |
attr=item | |
)) | |
def __getattr__(self, item): | |
""" | |
Tries to return a object attribute or a object key. | |
""" | |
try: | |
return self.__getattribute__(item) | |
except AttributeError: | |
return self._get_value_from_key(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment