How to make a decorator with or without parameters in python
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it. Decorators also can help you to reduce duplication on code.
In this article i’ll give some example how to write decorator with parameter or without parameter in python, learning this tool will help you so much in real project when you working in large code base that need some additional functionality without change it. It will like box inside the box.
I will use python native module from functools for wrapping my main function.
Decorator Without Parameter
This example will print double message “hello world” in given function.
In this decorator code i will run this function twice, and this is my main function.
Here you can see how to call the decorator using just “@function_name”, put it above the function and this decorator will execute right before the main function is executed and this is the result. This function will be executed twice. How easy is it ?? 😀
Decorator with parameters
Then we may think, what about we want to print this message based on the parameters, we can determine how much this message will be printed.
From earlier example, it just need to change little bit our decorator to support that feature.
In this change I just wrapped the previous decorator with one outline function to support the parameters, I will set the default loop as 1. So with this little change I can specify the number of times this main function will run with respect to the given parameter.
my main function is still the same as before but changed the decorator and added a new parameter called “repeat” as we defined earlier.
So when I run this code, it will execute as many parameters as given. This is the result.
See we can change or manipulate the result of the function without changing the main code by using decorators. Cool isn’t it ?😎 this can be implemented in any function that requires this same functionality without duplicating our code.
functools - Higher-order functions and operations on callable objects - Python 3.10.4 documentation
Source code: Lib/functools.py The module is for higher-order functions: functions that act on or return other…