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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Feb 19 09:54:53 CET 2009


En Thu, 19 Feb 2009 01:29:17 -0200, Alan G Isaac <alan.isaac at gmail.com>
escribió:

> 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?
>
>    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

The problem with using __setattr__ is that is slows down *all* attribute
writes considerably.

In particular, your code prevents using class attributes as a default
value for instance attributes (not a big deal, but I like it sometimes),
and you must remember to set a value for all attributes (even the "hidden"
ones used by any property). But if you feel OK with that, "just do it". I
think there are a few recipes in the Python Cookbook about this topic too.

-- 
Gabriel Genellina




More information about the Python-list mailing list