Course contentsShow
← Python
Lesson 659 of 1,06010. Advanced Language FeaturesFree lesson

Intercepting Class Creation with Metaclasses

Learners will define a custom metaclass to intercept and modify class creation processes before the class object is finalized in memory.

In this lesson, you will learn how to use metaclasses to intercept and modify your classes at the exact moment they are being created by the Python interpreter.

Understanding Metaclasses

Normally, when you define a class using class MyClass: ..., Python creates the class object automatically. A metaclass is essentially the "class of a class." It defines the blueprint for how a class object is constructed. By defining your own metaclass and assigning it to a class, you gain the power to inspect, inject, or even alter class attributes before the class is ever finished being built.

Intercepting with __new__

To intercept creation, you create a class that inherits from type and override its __new__ method. This method receives the name of the class, the base classes, and a dictionary of the class attributes (attrs).

class AttributeModifier(type):
    def __new__(cls, name, bases, attrs):
        # We can modify the class dictionary before it's created
        attrs['created_at'] = '2023-10-27'
        attrs['greet'] = lambda self: "Hello from the modified class!"
        
        # Finally, pass control back to the type constructor
        return super().__new__(cls, name, bases, attrs)

# Apply the metaclass using the 'metaclass' keyword
class MyApp(metaclass=AttributeModifier):
    pass

obj = MyApp()
print(obj.created_at)  # Output: 2023-10-27
print(obj.greet())     # Output: Hello from the modified class!

Why use this?

This technique is the backbone of many advanced frameworks. Instead of manually repeating code in every class (like registering models in an ORM or validating class structure), you can write a metaclass that automatically scans attrs and enforces rules or registers the class in a global registry. Because this happens at definition time (when the script is first loaded), you can catch configuration errors immediately rather than waiting for an instance to be created.

Key Takeaway: By overriding __new__ in a class inheriting from type, you can intercept the class creation process to inject attributes or perform validation logic before the class object is finalized.