yes, with metaclasses (was Re: Read-only class definitions?)

Alex Martelli aleax at aleax.it
Fri Oct 11 12:15:57 CEST 2002


<posted & mailed>

Troels Therkelsen wrote:

> 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.

In 2.2.* (and later), a class IS a class instance -- the class of
the class is also known as its _metaclass_.  Inherit from the
builtin type named 'type', override whatever you wish, and make
your new metaclass the class's metaclass (by setting __metaclass__
in class body, or inheriting from another class with that custom
metaclass, etc).

Example:

class metaNoDel(type):
    def __delattr__(self, name):
        raise TypeError, "Can't delete attr %s from NoDel class!" % name

class NoDel:
    __metaclass__ = metaNoDel

class a(NoDel):
    def afunc(self):
        pass

class b(a):
    pass

c = b()
c.afunc()
del a.afunc
c.afunc()

[alex at lancelot bnuma1]$ python nod.py
Traceback (most recent call last):
  File "nod.py", line 17, in ?
    del a.afunc
  File "nod.py", line 3, in __delattr__
    raise TypeError, "Can't delete attr %s from NoDel class!" % name
TypeError: Can't delete attr afunc from NoDel class!
[alex at lancelot bnuma1]$


Alex





More information about the Python-list mailing list