In this lesson, you will learn how to create class decorators that act as architectural gatekeepers, ensuring every class you decorate adheres to a specific structure or interface at runtime.
The Concept
While Python is dynamically typed, we often need to ensure that certain classes implement required methods or attributes to maintain architectural integrity. A class decorator is a function that takes a class as an input, modifies it (or validates it), and returns the modified class. By inspecting the class dictionary (cls.__dict__) during the class definition process, we can programmatically enforce that specific methods exist before the class is ever instantiated.
Enforcing an Interface
Suppose you have a set of "Plugin" classes that must implement a run method. Instead of relying on documentation, you can build a decorator to enforce this check automatically:
def enforce_run_method(cls):
if not hasattr(cls, 'run'):
raise TypeError(f"Class {cls.__name__} is missing the required 'run' method.")
return cls
@enforce_run_method
class DataProcessor:
def run(self):
print("Processing data...")
# This would raise a TypeError:
# @enforce_run_method
# class BrokenProcessor:
# pass
Injecting Functionality
Beyond validation, class decorators can inject methods dynamically. If you want every class with a specific decorator to have a timestamped get_metadata method, you can assign it directly to the class object:
import datetime
def add_timestamp(cls):
def get_metadata(self):
return f"Created at: {datetime.datetime.now()}"
cls.get_metadata = get_metadata
return cls
@add_timestamp
class User:
pass
# Usage
u = User()
print(u.get_metadata())
By intercepting the class creation, you gain the power to mandate strict adherence to patterns or "auto-fill" common functionality across entire modules. This acts as a compile-time check for your design patterns, catching missing interfaces long before your program enters the production environment.
Key Takeaway: Class decorators allow you to programmatically inspect and mutate classes at runtime, providing a powerful mechanism to enforce interfaces and inject shared behaviors across your codebase.