Creating new types and invoking super

Guilherme Polo ggpolo at gmail.com
Wed Jan 23 15:55:04 EST 2008


Hello,

Before starting, let me show some sample codes so I can explain:

class A(object):
    def __init__(self):
        super(A, self).__init__()

x = type("X", (A, ), {})()

This works fine, but suppose I have several classes like A and I would
like to create a decorator to call super. First I tried this:

def init(func):
    def _init(inst):
        super(inst.__class__, inst).__init__()
        func(inst)

    return _init

class A(object):
    @init
    def __init__(self): pass

This works when I create a instance by doing A(), but I get
"RuntimeError: maximum recursion depth exceeded" when I create a new
type doing type("X", (A, ), {}) and then create an instance of it.
To "solve" this problem, I changed the init function to this then:

def init(func):
    def _init(inst):
        super(inst.__class__.__mro__[-2], inst).__init__()
        func(inst)

    return _init

It works if A is a direct subclass of object, if it is not I have to
adapt the index [-2].
So, is there a better way to do this ?

-- 
-- Guilherme H. Polo Goncalves



More information about the Python-list mailing list