Read-only class definitions?

Troels Therkelsen t_therkelsen at hotmail.com
Fri Oct 11 06:04:19 EDT 2002


Hi list,

I'm wondering if there is a way to make class definitions read-only.  I know
you can protect class instances with __setattr__ et al, but these only work
on class instances.

I am using Python 2.2.1.

Take this, highly simplified, example:

>>> class a(object):
...   def afunc(self):
...     pass
... 
>>> class b(a):
...   pass
...
>>> c = b()
>>> c.afunc()
>>> del a.afunc
>>> c.afunc()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'b' object has no attribute 'afunc'

Now, this is not an error.  But I want to be able to prevent the situation
from occuring in the first place, because the same class can be used by
many different class instances, and I don't want one class instance to be
able to 'destroy' the class definition, thereby affecting all other class
instances which use that class definition.

Ideally, I want to be able to copy the behaviour of built-in types:

>>> object.__setattr__ = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't set attributes of built-in/extension type 'object'

But I don't know if that is possible from the Python side.  The new module
doesn't seem to provide any such flag to new.class().

The way I have solved it for the moment is with a factory function which
creates a copy of the superclass.  This way, two classes which subclass the
same superclass can modify the copy and it will not take effect globally in
any way.

However, this solution seems inelegant to me.

Anyone have any ideas? :-)


Regards,

Troels Therkelsen




More information about the Python-list mailing list