Warning when new attributes are added to classes at run time

Bruno Desthuilliers onurb at xiludom.gro
Thu Jul 20 04:32:28 EDT 2006


Matthew Wilson wrote:
> I sometimes inadvertently create a new attribute on an object rather
> update a value bound to an existing attribute.  For example:
> 
(snip)
> 
> I meant to update c.a but I created a new c.A.  I make this mistake
> probably hourly.
> 
> I suspect adding attributes at run time can be a beautiful thing, but in
> this particular instance, I'm only using this feature to hurt myself.

See other posts in this thread for some other possible solutions.

> I wrote a simple class that will warn me when I make this mistake in the
> future:
> 
>     import warnings
> 
>     class C(object):
> 
>         warn_on_new_attributes = True
> 
>         standard_attributes = []
> 
>         def __setattr__(self, name, value):
> 
>             if self.warn_on_new_attributes \
>                 and name is not 'warn_on_new_attributes' \
>                 and name not in self.standard_attributes:
> 
>                 warnings.warn("%s has no standard attribute %s."
>                               % (self.__class__.__name__, name))
> 
> 
>             self.__dict__[name] = value
Make it:	
              object.__setattr__(self, name, value)

Your approach will lead to strange results if you mix it with properties
or other descriptors...


>     class C1(C):
> 
>         standard_attributes = ['a1', 'a2']

DRY violation here. And a potential problem with inheritance (as always
with class attributes).

(snip)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list