[Python-Dev] Metaclasses, customizing attribute access for classes

Thomas Heller thomas.heller@ion-tof.com
Thu, 30 Mar 2000 21:30:25 +0200


Dear Python-developers,

Recently I played with metaclasses from within python,
also with Jim Fulton's ExtensionClass.
I even tried to write my own metaclass in a C-extension, using the
famous Don Beaudry hook.
It seems that ExtensionClass does not completely what I want.
Metaclasses implemented in python are somewhat slow,
also writing them is a lot of work.
Writing a metaclass in C is even more work...

Well, what do I want?

Often, I use the following pattern:
class X:
    def __init__ (self):
        self.delegate = anObjectImplementedInC(...)

    def __getattr__ (self, key):
        return self.delegate.dosomething(key)

    def __setattr__ (self, key, value):
        self.delegate.doanotherthing(key, value)

    def __delattr__ (self, key):
        self.delegate.doevenmore(key)

This is too slow (for me).
So what I would like do to is:

class X:
    def __init__ (self):
        self.__dict__ = aMappingObject(...)

and now aMappingObject will automatically receive
all the setattr, getattr, and delattr calls.

The *only* thing which is required for this is to remove
the restriction that the __dict__ attribute must be a dictionary.
This is only a small change to classobject.c (which unfortunately I
have only implemented for 1.5.2, not for the CVS version).
The performance impact for this change is unnoticable in pystone.

What do you think?
Should I prepare a patch?
Any chance that this can be included in a future python version?

Thomas Heller