Skip to content

Instantly share code, notes, and snippets.

@qoda
Last active August 29, 2015 13:56
Show Gist options
  • Save qoda/9112312 to your computer and use it in GitHub Desktop.
Save qoda/9112312 to your computer and use it in GitHub Desktop.
Convert Dict to Object
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
@qoda
Copy link
Author

qoda commented Feb 20, 2014

Don't use this!!! It's memory hungry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment