Decorators with parameters in Python
We know Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. In this article, we will learn about the Decorators with Parameters with help of multiple examples.
Python functions are First Class citizens which means that functions can be treated similarly to objects.
- Function can be assigned to a variable i.e they can be referenced.
- Function can be passed as an argument to another function.
- Function can be returned from a function.
Decorators with parameters is similar to normal decorators.
The syntax for decorators with parameters :
@decorator(params) def func_name(): ''' Function implementation'''
The above code is equivalent to
def func_name(): ''' Function implementation''' func_name = (decorator(params))(func_name) """
As the execution starts from left to right decorator(params) is called which returns a function object fun_obj. Using the fun_obj the call fun_obj(fun_name) is made. Inside the inner function, required operations are performed and the actual function reference is returned which will be assigned to func_name. Now, func_name() can be used to call the function with decorator applied on it.
How Decorator with parameters is implemented
Here params can also be empty.
Observe these first :
Inside decorator Inside inner function Decorated the function Inside actual function
Let’s move to another example:
Inside decorator Inside inner function I like geeksforgeeks Inside actual function
I like Geeksforgeeks Summation of values - 27 Geeks for Geeks
This example also tells us that Outer function parameters can be accessed by the enclosed inner function.
Decorator for 'stringJoin' Decorator for 'summation' stringJoin started ... I like Geeksforgeeks summation started ... 1729
1. Inside the Decorator
2. Inside the function
Note: Image snapshots are taken using PythonTutor.