design question: no new attributes

Harold Fellermann dadapapa at googlemail.com
Thu Mar 15 08:11:56 CET 2007


Hi Alan,

> One last point. While I remain interested in examples of how
> "late" addition ofattributesto class instances is useful,
> I must note that everyone who responded agreed that it
> has been a source of bugs.  This seems to argue against a
> general ban on "locking" objects in some way, in some
> circumstances.

If you want to restrict "late" addition of attributes, no-one will
prevent you to do so.
Arnaud has already given you an example implementation. Here is mine:

>>> class Foo(object) :
...
...     _locked = False
...
...     def __setattr__(self,attr,var) :
...         if self._locked and not attr in dir(self):
...             raise RuntimeError
...         else :
...             object.__setattr__(self,attr,var)
...
...     def lock(self) :
...         self._locked = True
...
>>> foo = Foo()
>>> foo.bar = 'allowed'
>>> foo.lock()
>>> foo.spam = 'fails'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in __setattr__
NotImplementedError
>>>
>>> foo.bar = 'still works'


See how it works? The lock method *dynamically* adds the attribute
foo._locked *after* initialization to the instance. Before the call
of foo.lock() foo._locked is a class attribute. Now you might argue
that one should better set foo._locked = False in the __init__ method
rather than as a class attribute. Something like:

class Foo(object) :
    def __init__(self) :
        self._locked = False

But no! The initialization would trigger
Foo.__setattr__(foo,'_locked',False)
which naturally runs into an attribute error since __setattr__ looks
up this
attribute. So this very same implementation is one of the pro examples
you
asked for :-)


cheers,

- harold -




More information about the Python-list mailing list