Overriding of the type.__call__() method in a metaclass

Marco Buttu marco.buttu at gmail.com
Sun Oct 6 14:17:33 EDT 2013


Hi all, I have a question about class creation and the __call__ method. 
I have the following metaclass:

 >>> class FooMeta(type):
...     def __call__(metacls, name, bases, namespace):
...         print("FooMeta.__call__()")


 From what I undestood, at the end of the class statement happens 
something like this:

 >>> def __call__(metacls, name, bases, namespace):
...     print("FooMeta.__call__()")
...
 >>> FooMeta = type('FooMeta', (type,), {'__call__': __call__})

The call to the metaclass type causes the call to type.__call__(), so 
that's happened is:

 >>> FooMeta = type.__call__(type, 'FooMeta', (type,), {'__call__': 
__call__})

Now I expected the output `FooMeta.__call__()` from the following Foo 
class creation:

 >>> class Foo(metaclass=FooMeta):
...     pass

because I thought at the end of the class Foo suite this should have 
been happened:

 >>> Foo = FooMeta.__call__(FooMeta, 'Foo', (), {})
FooMeta.__call__()

but I thought wrong:

 >>> class FooMeta(type):
...     def __call__(metacls, name, bases, namespace):
...         print("FooMeta.__call__()")
...
 >>> class Foo(metaclass=FooMeta):
...     pass
...
 >>>

How come? Is it because the first argument of metaclass.__call__() is 
always type or I am thinking something wrong?
Thanks in advance, Marco
-- 
Marco



More information about the Python-list mailing list