Python Decorators: When to use and when to avoid them
Decorators are used in Python to enhance or modify the way functions and classes behave. Essentially they are used to add more functionalities to existing functions without modifying the functions' source codes. To define a decorator, you simply append the symbol @
before your decorator function name.
A decorator is also defined as a function that accepts another function as an argument and return a new function. In the example below, a decorator function called greeting
takes a function func
as an argument. Within the greeting
, an inner function called wrapper
containing the additional functionality we want to add is defined. In this case, a message is printed before and after the original function is called.
The decorator function greeting
returns the wrapper
function replacing the original function with the decorated form. To apply the decorator, we place the @greeting
syntax on top of welcome
function.
To further enhance our function, we can pass arguments to the original as well as the decorator function as follows:
When to use Decorators
- When you want you add common functionality to multiple functions without duplicating codes. For example logging, input validation, caching, etc.
- When you want to modify a function or a class behaviour without changing the original source code of the function.
- When you want to properly organize your code and improve maintainability by separating concerns such as authorization from the core logic of your function or class.
Common use cases for Decorators
- Logging - Decorators are commonly used to log functions' calls and return their values.
- Input Validation - Decorators can be used to validate the expected argument type when a function is called.
- Authorization - Decorators can also be used to verify if a user is authorized to access a function.
When to avoid Decorators
- Excessive use of decorators can make code complex to maintain. Avoid decorators where simple explicit function calls are sufficient.
- When decorators impact on code performance is evaluated to be significant, consider alternative approaches.
- Avoid decorators if it is determined that their usage can introduce tight coupling (binding) between decorators and decorated functions or classes.