Is it possible to inheret a metaclass.

Pieter van Oostrum pieter-l at vanoostrum.org
Fri Apr 10 08:19:19 EDT 2020


Antoon Pardon <antoon.pardon at vub.be> writes:

> Op 9/04/20 om 18:37 schreef Peter Otten:
>> Antoon Pardon wrote:
>> 
>>> I am experimenting with subclasses that all need the same metaclass as the
>>> base class. Is there a way to make the metaclass be inherited, so that you
>>> don't have to repeat the "metaclass = MetaClass" with every subclass.
>> ?
>> This is not only possible, this is the default:
>>   >>> class Pardon(type): pass
>> ...
>>>>> class A(metaclass=Pardon): pass
>> ...
>>>>> class B(A): pass
>> ...
>>>>> type(B)
>> <class '__main__.Pardon'>
>
> Can you explain what is wrong with the code below:
>
> This produces only: Calling Pardon with A.
>
>
> def Pardon(cls, *args):
>     print("Calling Pardon with", cls)
>     return type(cls, *args)
>
> class A(metaclass=Pardon): pass
>
> class B(A): pass
>
Your Pardon is not a class, it is a function. Class A is created by type(cls, *args), so 'type' is the metaclass of A, and therefore also of B.
Creation of B does not call Pardon.

I find it peculiar that you can give a function as metaclass. But that seems to be part of the specification. The function result is what the 'class' becomes. You can even have it return something else. Then the 'class' wouldn't really be a class.

In [65]: def meta(cls, *args): return 1

In [66]: class A(metaclass=meta): pass

In [67]: A
Out[67]: 1

-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list