Is there a way in python to determine if a class object is a metaclass?
I know that you could check using the equality operator. metaclass == type
But that wouldn't cover for user defined metaclasses.
Test if the object is a subclass of type
:
issubclass(MetaClass, type)
This returns True
for all metaclasses, including type
itself.
Demo:
>>> class Meta(type): pass
...
>>> class Foo(object): pass
...
>>> issubclass(Meta, type)
True
>>> issubclass(Foo, type)
False
Most metaclasses are type
subclasses (issubclass(metaklass, type)
) but not all:
>>> def logging_meta(name, bases, namespace, **kwd):
... print(name, bases, namespace, kwds)
... return type(name, bases, namespace, **kwds)
...
>>> class C(metaclass=logging_meta):
... a = 1
...
C () {'__module__': '__main__', '__qualname__': 'C', 'a': 1} {}
>>> issubclass(logging_meta, type)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: issubclass() arg 1 must be a class
i.e., the answer is "any callable e.g., a class with a __call__()
method that accepts the same arguments as type()
and returns a class object will do":
>>> class C(metaclass=lambda *a: lambda *a: None): pass
...
>>> C()
>>> type(C)
<class 'function'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With