Python decorator is just a function which is called before another function.
Basically, decorator is used in python to modify a function using another function.
Creating Custom Python Decorator
print("in the decorator")
print("after the decorator")
print("I m the function!")
Here, I have first created my own decorator @my_decorator, which takes a function as a parameter. The function on which we will apply this decorator will automatically be passed as an argument. We don’t need to do that manually.
In my_decorator, I have created another function function_that_runs_func(), which will replace the original my_function().
Note: In order to replace my_function() with its modified form, we need to apply the decorator at the starting of the function declaration. And the same decorator should return modified my_function so that it my_function can be replaced with it. That’s why we are returning function_that_runs_func at the end of our custom decorator i.e my decorator.
If you call my_function you will get following output.
in the decorator
I m the function!
after the decorator
The above program is tested in python 3 and is giving proper output as expected.