challenging (?) metaclass problem

alainpoint at yahoo.fr alainpoint at yahoo.fr
Mon Apr 10 09:06:19 EDT 2006


Now, a tab-free version of my previous post. (Sorry for the
inconvenience)
Hi,


I have what in my eyes seems a challenging problem.
Thanks to Peter Otten, i got the following code to work. It is a sort
of named tuple.
from operator import itemgetter
def constgetter(value):
        def get(self): return value
        return get
def createTuple(*names):
        class TupleType(type):
                pass
        class T(tuple):
                __metaclass__ = TupleType
                def __new__(cls, *args):
                        if len(names) != len(args):
                                raise TypeError
                        return tuple.__new__(cls, args)
        for index, name in enumerate(names):
                setattr(T, name, property(itemgetter(index)))
                setattr(TupleType, name, property(constgetter(index)))
        return T
if __name__ == '__main__':
        Point=makeTuple('x','y')
        p=Point(4,7)
        assert p.x==p[0]
        assert p.y==p[1]
        assert Point.x==0
        assert Point.y==1


Now my problem is the following. I want to write a function called
createDerivedTuple in order to create a class derived from the one
created with the function createTuple, taking the parent class as first

argument:
def createDerivedTuple(parentclass,*names):
        ....... code yet to be figured out ....


The usage should be as follows:


DerivedPoint=makeDerivedTuple(Point,'z')
p=DerivedPoint(4,7,9)
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
assert DerivedPoint.x==0
assert DerivedPoint.y==1
assert DerivedPoint.z==2


I am still a newbie on metaclasses but i am convinced there are elegant

solutions to this challenging problem. 


Best regards 


Alain




More information about the Python-list mailing list