Class Variable Question
Carlos Alberto Reis Ribeiro
cribeiro at mail.inet.com.br
Mon Apr 9 22:23:16 EDT 2001
At 19:24 09/04/01 -0400, Douglas Alan wrote:
>I'm not arguing against "programmer freedom". I'm arguing for
>features that reduce bugs without reducing power.
That's the point. Because of the way Python works, it is almost impossible
to implement any kind of "attribute checking". My own code is filled with
this kind of construct. You can build new classes on the fly, make
composite objects, a whole lot of things that are nearly impossible to do
using other statically typed languages.
If you really think that this is a good idea (and I understand your
position for some particular cases), put some checks on the __setattr__ of
your class. It will trap all occurrences of new attributes being attached
to the class instance. This is a quick example, by no means complete, that
shows the concept:
--- test-lock-attr.py
class NonExtensibleClass:
def __setattr__(self, attr, value):
if hasattr(self, '_locked') and not (self.__dict__.has_key(attr)):
raise AttributeError
else:
self.__dict__[attr] = value
def lock(self):
self._locked = 1
class MyClass(NonExtensibleClass):
def __init__(self):
self.x = 1
self.y = 0
--- testing
>>> m = MyClass()
>>> m.x, m.y
(1, 0)
>>> m.a
Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'MyClass' instance has no attribute 'a'
>>> m.a = 2
>>> m.a
2
>>> m.lock()
>>> m.b = 3 # you can't insert any new attribute
Traceback (innermost last):
File "<interactive input>", line 1, in ?
File "E:\WORK\Python\teste-lock-attr.py", line 7, in __setattr__
raise AttributeError
AttributeError:
>>> m.a = 4 # you can still change attributes
>>> m.a
4
You can put the lock() call inside __init__ to achieve automatic locking.
Carlos Ribeiro
More information about the Python-list
mailing list