In this lesson, you will learn how to intercept and modify the creation of a class by implementing the __new__ method within a metaclass.
The Role of __new__ in Metaclasses
When you define a class, Python uses a metaclass (by default type) to construct the class object itself. By creating your own metaclass and defining __new__, you gain the power to "mutate" the class before it even exists in memory. This is the stage where you can inject new attributes, force base class changes, or perform validation on the class body.
Unlike __init__, which initializes an object that has already been created, __new__ is a static method that is responsible for creating the object. When defined in a metaclass, its signature looks like this: def __new__(mcs, name, bases, namespace).
Practical Injection
Imagine you want every class that uses your metaclass to automatically have a "registry" attribute or a specific base class. You can inject these directly into the namespace dictionary before passing it to the superclass constructor.
class MetaRegistry(type):
def __new__(mcs, name, bases, namespace):
# Inject an attribute into the class
namespace['is_registered'] = True
# We can even modify the bases tuple to enforce inheritance
return super().__new__(mcs, name, bases, namespace)
class MyComponent(metaclass=MetaRegistry):
pass
print(MyComponent.is_registered) # Output: True
In this example, the MetaRegistry intercepts the creation process. By adding is_registered to the namespace dictionary, every class using this metaclass inherits that attribute automatically. This is a powerful mechanism for building frameworks where you need to enforce structure across many different classes without manual boilerplate.
Because __new__ returns the newly created class object, you are effectively controlling the final structure of the class definition itself. You are no longer just configuring instances; you are configuring the blueprint of the objects.
Key Takeaway: Implementing __new__ in a metaclass allows you to programmatically modify the namespace or base classes of a class definition at the exact moment of its creation.