Calling super() in __init__ of a metaclass

Peter Otten __peter__ at
Sat Aug 6 10:11:49 CEST 2011

Eli Bendersky wrote:

> Consider this standard metaclass definition:
> class MyMetaclass(type):
>     def __init__(cls, name, bases, dct):
>         super(MyMetaclass, cls).__init__(name, bases, dct)
>         # do meta-stuff
> class Foo(object):
>     __metaclass__ = MyMetaclass
> The call "super(MyMetaclass, cls)" should returns the parent of
> MyMetaclass here. But the 'cls' passed into this __init__ is *not*
> MyMetaclass, but rather the created class - i.e. Foo. So how does
> "super" get to the parent of MyMetaclass using this information? The
> documentation of "super" says:
>     If the second argument is a type, issubclass(type2, type) must be
> true (this is useful for classmethods).
> Yes, 'cls' is a type (it's "class Foo"), but no, it's not a subclass
> of MyMetaclass, so this doesn't help.

Don't let yourself get confused by the name 'cls' for what is normally 
called 'self'. Foo is an instance of MyMetaclass, so the situation is 
exactly the same as in

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

I don't know how exactly super() is implemented, but to go from an instance 
to its class you can use type(instance) or instance.__class__.

More information about the Python-list mailing list