Finally, I found how to do that. I created a class inheriting from dict
and made it create its attributes (with setattr
) based on the data contained in the dict. The class code is :
class IdentityDictionary(dict):
"""
Create a custom dict with the identities of a user.
Identities are accessible via attributes or as normal dict's key/value.
"""
def __init__(self, user, key='service_name'):
identities = UserIdentity.objects.filter(user=user)
dict_identities = dict([ (getattr(user_id.identity, key).replace(' ', '').lower(), user_id.identity) for user_id in identities ])
super(IdentityDictionary, self).__init__(dict_identities)
for id_name, id_value in dict_identities.items():
setattr(self, id_name, id_value)
Then I made a mixin to add to the user class:
class IdentitiesMixin(object):
"""
Mixin added to the user to retrieve identities
"""
_identities_dict = {}
_is_identities_initialized = False
@property
def identities(self):
if not self._is_identities_initialized :
self._identities_dict = IdentityDictionary(self)
self._is_identities_initialized = True
return self._identities_dict
One more point: the custom dict is not intended for reusability : attributes are not updated if the dict
is (hopefully, it is not a problem with the class use cases).