block dynamic attribute creation

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Feb 19 03:47:48 EST 2009

Alan G Isaac a écrit :
> 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?
>   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

Might be safer to call on the parent class __setattr__ instead of 
directly assigning to the instance's dict Also, your tests in the except 
clause could be simplified:

       if not hasattr(self, attr) and getattr(self, '_attrlock', False):
         raise AttributeError(yadda yadda)
       # NB: assume newstyle class
       super(YourClass, self).__setattr__(attr, val)

My 2 cents.

More information about the Python-list mailing list