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

Intercepting Class Attributes with Metaclass Hooks

Use the prepare and new methods to dynamically modify or validate class attributes during the class construction phase.

In this lesson, you will learn how to intercept and modify class attributes during the class creation process by leveraging __prepare__ and __new__ in your metaclasses.

The Power of Interception

When Python defines a class, it first gathers all the class body attributes into a namespace. By customizing this process, you can validate, transform, or restrict attributes before the class object is even created.

The process happens in two distinct steps:

  1. __prepare__: This is a static method that returns the dictionary-like object used to store class attributes as they are parsed.
  2. __new__: This is where the class is actually "born." It receives the class name, the base classes, and the finalized attribute dictionary, allowing you to filter or sanitize the attributes.

A Practical Example

Imagine you want to ensure that every class using your metaclass has all its attributes defined in uppercase to enforce a naming convention.

class UpperCaseMeta(type):
    @classmethod
    def __prepare__(mcs, name, bases):
        # We can return a custom dictionary-like object here if needed
        return {}

    def __new__(mcs, name, bases, attrs):
        # Intercept and transform attributes before class creation
        upper_attrs = {
            (k.upper() if not k.startswith('__') else k): v 
            for k, v in attrs.items()
        }
        return super().__new__(mcs, name, bases, upper_attrs)

class Config(metaclass=UpperCaseMeta):
    port = 8080
    host = 'localhost'

print(Config.PORT)  # Output: 8080
print(Config.HOST)  # Output: localhost

Why Use This?

By using these hooks, you move validation from runtime (where errors might trigger late) to the class definition phase (where errors trigger immediately upon execution). This is perfect for creating robust frameworks or DSLs (Domain Specific Languages) where you need to enforce strict schemas for class variables, such as requiring specific data types or preventing illegal attribute names.

Key Takeaway: Metaclass hooks like __prepare__ and __new__ allow you to intercept the class definition process, enabling you to enforce architectural standards by dynamically transforming attributes before a class is initialized.