In this lesson, you will learn how to inject dynamic functionality into classes using decorators and compare this approach against metaclasses to choose the right tool for your design.
Class Decorators for Method Injection
A class decorator is simply a function that takes a class object as an argument, modifies it (like adding a new method), and returns it. This is a powerful, readable way to "plug in" features at runtime.
Consider a scenario where you want to add a greet method to various classes without modifying their source code:
def add_greeting(cls):
def greet(self):
return f"Hello from {self.__class__.__name__}!"
setattr(cls, 'greet', greet)
return cls
@add_greeting
class User:
pass
print(User().greet()) # Output: Hello from User!
Decorators vs. Metaclasses
When choosing between class decorators and metaclasses, think about scope and intent:
- Class Decorators: These are best when you want to "enhance" a class. They are simpler to read and maintain because they treat the class as an object that is passed through a function. Use them when you want to add methods, register classes, or wrap existing methods without needing to control the entire class construction process.
- Metaclasses: These operate at a deeper level by intercepting the class creation process via
__new__or__init__. You should reach for a metaclass when you need to enforce architectural constraints (like requiring specific methods), control the creation of the class namespace, or modify how classes inherit attributes.
If you only need to inject a few methods or attach a behavior, the decorator is your best friend—it avoids the "magic" and complexity associated with inheritance-based metaclass configurations. Metaclasses are reserved for when you must exert authority over the class creation itself, whereas decorators are for augmenting classes that have already been defined.
Key Takeaway: Use class decorators for simple feature injection to keep your code readable, and reserve metaclasses for when you need to intercept and modify the fundamental class creation process.