Class-Based Decorators - Make Your Python Code Classy
Av Idego Group

A decorator is fundamentally a function that accepts another function and performs some additional logic to extend or modify the original function's behavior. Understanding decorators requires familiarity with first-class functions and closures.
When a function accepts another function and may perform some logic before it or afterward, the decorator pattern emerges. The @decorator_function syntax is merely shorthand for original_function = decorator_function(original_function).
Class-based decorators consist of two dunder methods: __init__() for decorator instantiation and parameter handling, and __call__() for execution when the decorated object is invoked. Class-based decorators offer improved readability and better separation between decorator definition and wrapping logic compared to function-based alternatives.
The benefits of decorators align with the Don't Repeat Yourself principle. Once created, decorators are backward compatible and require no modifications to executing code—a significant advantage when updating multiple methods simultaneously.
A practical example demonstrates the @LogException decorator, which handles exceptions by logging them to files. This decorator accepts parameters like filename, file mode, and an optional timestamp flag, showcasing how parametrized decorators can be customized for various scenarios. The decorator elegantly wraps parsing methods without altering their implementation, enabling code reuse across numerous functions.