Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a class in python is a metaclass

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.

like image 968
Ben Hoff Avatar asked Sep 16 '25 00:09

Ben Hoff


2 Answers

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
like image 144
Martijn Pieters Avatar answered Sep 18 '25 16:09

Martijn Pieters


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'>
like image 28
jfs Avatar answered Sep 18 '25 17:09

jfs