Created
October 25, 2012 10:19
-
-
Save lgr/3951835 to your computer and use it in GitHub Desktop.
A dictionary which keys can be accessed and added as object attributes.
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
class AttributedDict(dict): | |
""" | |
A class extending the standard dict so that its keys can be accessed | |
as an object attributes (as long as the are strings). | |
Notice: this class is not pickable, so for example an attempt to save | |
its instance in Django session causes an error. | |
""" | |
__getattr__ = dict.__getitem__ | |
def __setattr__(self, key, value): | |
dict.__setitem__(self, key, self.__objectize(value)) | |
__setitem__ = __setattr__ | |
def __init__(self, *args, **kwargs): | |
dic = args | |
if args and type(args[0]) == dict: | |
dic = args[0] | |
for key, value in args[0].items(): | |
dic[key] = self.__objectize(value) | |
dic = (dic,) + args[1:] | |
super(AttributedDict, self).__init__(*dic, **kwargs) | |
@classmethod | |
def __objectize(cls, dic): | |
def is_dict(d): | |
return type(d) is dict | |
if not is_dict(dic) or dic.__class__ == AttributedDict: | |
return dic | |
for key, value in dic.items(): | |
dic[key] = cls.__objectize(value) | |
return AttributedDict(dic) | |
def get_dictionary(self): | |
res = {} | |
for key, value in self.items(): | |
if type(value) == AttributedDict: | |
value = value.get_dictionary() | |
res[key] = value | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment