Skip to content

Instantly share code, notes, and snippets.

@bogsio
Created October 28, 2013 19:32
Show Gist options
  • Save bogsio/7203093 to your computer and use it in GitHub Desktop.
Save bogsio/7203093 to your computer and use it in GitHub Desktop.
Understanding Python descriptors #4
class EmailField(object):
__current_id = 0 # unique id of the instance
__email_dict = {} # dict containing all email values
__dict_key = "__email_field_key" # name of member attached to instances
def __get__(self, instance, owner):
if not hasattr(instance, self.__class__.__dict_key):
return None
# Retrieve the email value from the dict
key_name = getattr(instance, self.__class__.__dict_key)
return self.__class__.__email_dict.get(key_name, None)
def __set__(self, instance, value):
if not hasattr(instance, self.__class__.__dict_key):
# We have a new instance with an email attached
setattr(instance, self.__class__.__dict_key, self.__class__.__current_id)
self.__class__.__current_id += 1
validate_email(value)
key_name = getattr(instance, self.__class__.__dict_key)
# save the new email value in the dict
self.__class__.__email_dict[key_name] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment