I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass like
def metacls(clsName, bases, atts):
....
return type(clsName, bases, atts)
However, I have seen a lot of people write their metaclasses in the following way:
class Metacls(type):
def __new__(meta, clsName, bases, atts):
....
return type.__new__(meta, clsName, bases, atts)
As far as I can see, these would both do the same thing. Is there any reason to use the base class instead? Is it customary?
There are subtle differences, mostly relating to inheritance. When using a function as a metaclass, the resulting class is really an instance of
type
, and can be inherited from without restriction; however, the metaclass function will never be called for such subclasses. When using a subclass oftype
as a metaclass, the resulting class will be an instance of that metaclass, as will any of its subclasses; however, multiple inheritance will be restricted.Illustrating the differences:
Note that when defining sub1 and sub2, no metaclass functions were called. They will be created exactly as if c1 and c2 had no metaclasses, but instead had been manipulated after creation.
Note the differences already: M1 was called when creating Sub1, and both classes are instances of M1. I'm using
super()
for the actual creation here, for reasons which will become clear later.This is the major restriction on multiple inheritance with metaclasses. Python doesn't know whether M1 and M2 are compatible metaclasses, so it forces you to create a new one to guarantee that it does what you need.
This is why I used
super()
in the metaclass__new__
functions: so each one can call the next one in the MRO.Certain use cases might need your classes to be of type
type
, or might want to avoid the inheritance issues, in which case a metaclass function is probably the way to go. In other cases, the type of the class might be truly important, or you might want to operate on all subclasses, in which case subclassingtype
would be a better idea. Feel free to use the style that fits best in any given situation.