Last active
August 29, 2015 13:56
-
-
Save qoda/9112312 to your computer and use it in GitHub Desktop.
Convert Dict to Object
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 AttrDict(dict): | |
""" | |
Convert a dict to an object. | |
""" | |
def __init__(self, new_dict): | |
self.__dict__.update(new_dict) | |
for key, val in new_dict.items(): | |
if isinstance(val, dict): | |
self.__dict__[key] = AttrDict(val) | |
else: | |
class AttrType(type(val)): | |
def __getattribute__(self, name): | |
try: | |
return object.__getattribute__(self, name) | |
except AttributeError: | |
return None | |
self.__dict__[key] = AttrType(val) | |
def __getattr__(self, attr, default=None): | |
return self.get(attr, default) | |
test_dict = { | |
'a': [1, 2, 3], | |
'b': { | |
'ba': 'f', | |
'bb': { | |
'bba': [1, 2], | |
'bbb': { | |
'bbba': 1 | |
} | |
} | |
}, | |
'c': 1 | |
} | |
test_obj = AttrDict(test_dict) | |
assert isinstance(test_obj.b, AttrDict) | |
assert test_obj.a == [1, 2, 3] | |
assert isinstance(test_obj.a, list) | |
assert test_obj.a.b is None | |
assert test_obj.b.ba == 'f' | |
assert isinstance(test_obj.b.ba, str) | |
assert test_obj.b.bb.bbb.bbba == 1 | |
assert isinstance(test_obj.b.bb.bbb.bbba, int) | |
assert test_obj.b.bb.bbb.bbbb is None | |
assert test_obj.b.bb.bbb.get('bbbb') is None | |
assert test_obj.b.bb.bbb.get('bbbb', 1.) == 1.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't use this!!! It's memory hungry.