block dynamic attribute creation (was: get descriptor from instance)

Alan G Isaac alan.isaac at gmail.com
Wed Feb 18 22:29:17 EST 2009


On 2/18/2009 6:15 PM Gabriel Genellina apparently wrote:
> type(a).x 

OK, that's good.  I'd like to sometimes lock attribute creation on
instances of a class but still allow properties to function
correctly.  Will something like below be satisfactory?

Thanks,
Alan

   def __setattr__(self, attr, val):
     """If instance locked, allow no new attributes."""
     try:
       #get the class attribute if it exists
       p = getattr(type(self),attr)
       #if it's a descriptor, use it to set val
       p.__set__(self, val)
     except AttributeError: #no descriptor
       if hasattr(self, attr): #update val
         self.__dict__[attr] = val
       elif getattr(self, '_attrlock', False):
         raise AttributeError(
         "Set _attrlock to False to add attributes.")
       else:
         #new attributes allowed
         self.__dict__[attr] = val



More information about the Python-list mailing list