What’s a Decorator?
Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects (e.g., functions) that process other callable objects. As we saw earlier in this book, Python decorators come in two related flavors:
- Function decorators do name rebinding at function definition time, providing a layer of logic that can manage functions and methods, or later calls to them.
- Class decorators do name rebinding at class definition time, providing a layer of logic that can manage classes, or the instances created by calling them later.
In short, decorators provide a way to insert automatically run code at the end of function and class definition statements—at the end of a def for function decorators, and at the end of a class for class decorators. Such code can play a variety of roles, as described in the following sections.