Summary
Decorators are powerful tools in Python that can be applied to many things such as classes, methods, functions, generators, and many more. We have demonstrated how to create decorators in different ways, and for different purposes, and drew some conclusions along the way.
When creating a decorator for functions, try to make its signature match the original function being decorated. Instead of using the generic *args
and **kwargs
, making the signature match the original one will make it easier to read and maintain, and it will resemble the original function more closely, so it will be more familiar to readers of that code.
Decorators are a very useful tool for reusing code and following the DRY principle. However, their usefulness comes at a cost, and if they are not used wisely, the complexity can do more harm than good. For that reason, we emphasize that decorators should be used when they are going to be applied multiple times (three or more times...