Advanced OOP
Class Decorators
Decorators that modify or enhance classes
Interview: Advanced patterns — tests understanding of decorator mechanics and class transformation
Class decorators are functions that take a class and return a modified class. They provide a cleaner alternative to metaclasses for many use cases. Common patterns include adding methods, wrapping methods, enforcing singletons, and registering classes. The @dataclass decorator is the most famous example.
How Class Decorators Work
- A function that takes a class as argument and returns a class
- Applied with
@decoratorsyntax above the class definition - Can modify the class in-place or return a new class
- Simpler and more explicit than metaclasses for most use cases
Class Decorators vs Metaclasses
- Decorators: Explicit, simple, don't affect inheritance
- Metaclasses: Affect all subclasses, more powerful but complex
- Prefer decorators when you don't need inheritance propagation
Interview Tip
Know the key difference: class decorators only affect the decorated class; metaclasses affect the class AND all its subclasses. Choose based on whether you need propagation.
Interview Tip
Know the key difference: class decorators only affect the decorated class; metaclasses affect the class AND all its subclasses. Choose based on whether you need propagation.
Use Cases
Singleton pattern without metaclass complexity
Auto-generating __repr__, __eq__, __hash__ (like @dataclass)
Logging/wrapping all public methods in a class
Plugin/handler registration systems
Adding validation, caching, or timing to class methods
Common Mistakes
Class decorators don't propagate to subclasses (use metaclasses for that)
Forgetting to return the class from the decorator function
Modifying class in-place vs replacing it (affects isinstance checks)
Losing the original class name/docstring when wrapping
Using class decorators when @dataclass or other stdlib options exist