Metaclasses
Classes are objects too, and a metaclass decides what happens when you call one.
- Explain that a class is an instance of type
- Trace what Parent('Kamran', 32) does, step by step
- Recognise when a metaclass is the right tool, and when it is not
In Python everything is an object, including classes. A class is an instance of its metaclass, which by default is type. Writing Parent('Kamran', 32) calls the class object, and calling an object runs its type’s __call__ — so object creation is controlled by type.__call__, which does two things:
-
obj = cls.__new__(cls, *args)— allocate the object, -
cls.__init__(obj, *args)— initialise it, ifobjis an instance ofcls.
Overriding call and forgetting the rest
01basics.py defines a metaclass whose __call__ only prints:
class MyMeta(type):
def __call__(self, *args, **kwargs):
print('{self.__name__} is called with args = {args}, kwargs = {kwargs}')
Neither __new__ nor __init__ ever runs, the method returns nothing, and parent ends up None — type(parent) is NoneType, exactly as the script’s comment says. 02basics_solution.py restores the two steps by hand:
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls, *args, **kwargs)
if isinstance(obj, cls):
cls.__init__(obj, *args, **kwargs)
return obj
and the output now shows new is called, init is called, and <class '__main__.Parent'>. The idiomatic version delegates to the parent metaclass, which does the same thing: return super().__call__(*args, **kwargs).
One thing the output gives away: both scripts print the literal text {self.__name__} is called with args = {args}, kwargs = {kwargs}. The strings are missing their f prefix, so the braces are never filled in. With f'{cls.__name__} is called with args = {args}, kwargs = {kwargs}' the line reads Parent is called with args = ('Kamran', 32), kwargs = {}.
When to reach for one
Metaclasses run when a class is created or called, so they suit framework work: registering every subclass automatically, enforcing that subclasses define certain methods, or building singletons. For most of those tasks, __init_subclass__ or a class decorator is simpler and easier to read; a good rule is to try those first.
Try it yourself. Write a Singleton metaclass whose __call__ stores the first instance in a dictionary keyed by class and returns it on every later call. Check that A() is A() is True. Then implement the same behaviour with __new__ alone and compare.