Decorators with parameters in Python
Last Updated :
27 Aug, 2024
Prerequisite: Decorators in Python, Function Decorators
We know Decorators are a very powerful and useful tool in Python since it allow programmers to modify the behavior of functions or classes. In this article, we will learn about the Decorators with Parameters with the help of multiple examples.
Python functions are First Class citizens which means that functions can be treated similarly to objects.
- The function can be assigned to a variable i.e. they can be referenced.
- The function can be passed as an argument to another function.
- The function can be returned from a function.
Decorators with parameters are 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 a decorator applied to it.
How Decorator with parameters is implemented
Python3
def decorators(*args, **kwargs):
def inner(func):
'''
do operations with func
'''
return func
return inner #this is the fun_obj mentioned in the above content
@decorators(params)
def func():
"""
function implementation
"""
Here params can also be empty.
Observe these first :
Python3
# Python code to illustrate
# Decorators basic in Python
def decorator_fun(func):
print("Inside decorator")
def inner(*args,**kwargs):
print("Inside inner function")
print("Decorated the function")
# do operations with func
func()
return inner()
@decorator_fun
def func_to():
print("Inside actual function")
func_to
OutputInside decorator
Inside inner function
Decorated the function
Inside actual function
Another Way:
Python3
# Python code to illustrate
# Decorators with parameters in Python
def decorator_fun(func):
print("Inside decorator")
def inner(*args, **kwargs):
print("Inside inner function")
print("Decorated the function")
func()
return inner
def func_to():
print("Inside actual function")
# another way of using decorators
decorator_fun(func_to)()
OutputInside decorator
Inside inner function
Decorated the function
Inside actual function
Let's move to another example:
Example 1:
Here is the code Explaination
decorator(like)
: The decorator function now directly accepts the parameter like
.inner(func)
: This function wraps the actual function func
and uses the parameter like
within its scope.wrapper()
: The wrapper
function is used to call the actual func
, and it is returned from the inner
function.
Python
# Python code to illustrate
# Decorators with parameters in Python
def decorator(like):
print("Inside decorator")
def inner(func):
# code functionality here
print("Inside inner function")
print("I like", like)
def wrapper():
func()
return wrapper
# returning inner function
return inner
@decorator(like="geeksforgeeks")
def my_func():
print("Inside actual function")
# Call the decorated function
my_func()
OutputInside decorator
Inside inner function
I like geeksforgeeks
Inside actual function
Example 2:
Here is the code Explaination
decorator_func(x, y)
: This is a decorator factory. It takes two parameters, x
and y
, and returns a decorator.Inner(func)
: This is the actual decorator returned by decorator_func
. It takes a function func
and defines a wrapper
function around it.wrapper(*args, **kwargs)
: This function is executed when the decorated function is called. It prints some messages and the summation of x
and y
before calling the original function func
.return wrapper
: The wrapper
function is returned by the Inner
function.return Inner
: The Inner
decorator is returned by decorator_func
.decorator_func(12, 15)(my_fun)('Geeks', 'for', 'Geeks')
: This line applies the decorator with the parameters 12
and 15
to my_fun
. The decorator prints the message and summation before calling my_fun
with the arguments 'Geeks'
, 'for'
, 'Geeks'
.
Python3
# Python code to illustrate
# Decorators with parameters in Python
def decorator_func(x, y):
def Inner(func):
def wrapper(*args, **kwargs):
print("I like Geeksforgeeks")
print("Summation of values - {}".format(x+y) )
func(*args, **kwargs)
return wrapper
return Inner
# Not using decorator
def my_fun(*args):
for ele in args:
print(ele)
# another way of using decorators
decorator_func(12, 15)(my_fun)('Geeks', 'for', 'Geeks')
OutputI like Geeksforgeeks
Summation of values - 27
Geeks
for
Geeks
Example 3:
Here is the code Explaination
- Decorator Function
type_check_decorator
:- Parameter:
expected_type
specifies the type that all arguments should be. - Inner Function
decorator
: Takes the function func
to be decorated. - Wrapper Function
wrapper
: Checks if all arguments are of expected_type
and calls func
if they are; otherwise, returns "Invalid Input"
.
- Decorated Functions:
string_join
: Joins all string arguments into one string.summation
: Sums up all integer arguments.
- Function Calls:
string_join("I ", 'like ', "Geeks", 'for', "geeks")
: Concatenates strings correctly.summation(19, 2, 8, 533, 67, 981, 119)
: Sums integers correctly.
Python
# Simple decorator with parameters
def type_check_decorator(expected_type):
def decorator(func):
def wrapper(*args, **kwargs):
if all(isinstance(arg, expected_type) for arg in args):
return func(*args, **kwargs)
return "Invalid Input"
return wrapper
return decorator
@type_check_decorator(str)
def string_join(*args):
return ''.join(args)
@type_check_decorator(int)
def summation(*args):
return sum(args)
# Test the functions
print(string_join("I ", 'like ', "Geeks", 'for', "geeks"))
print(summation(19, 2, 8, 533, 67, 981, 119))
OutputI like Geeksforgeeks
1729
1. Inside the Decorator

2. Inside the function

Note: Image snapshots are taken using PythonTutor.
Similar Reads
Nested Decorators in Python
Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value. Nes
2 min read
Data Classes in Python | Set 2 (Decorator Parameters)
Prerequisite: Data Classes in Python | Set 1 In this post, we will discuss how to modify the default constructor which dataclass module virtually makes for us. dataclass() decorator - @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) By changing t
4 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Memoization using decorators in Python
Recursion is a programming technique where a function calls itself repeatedly till a termination condition is met. Some of the examples where recursion is used are a calculation of fibonacci series, factorial, etc. But the issue with them is that in the recursion tree, there can be chances that the
3 min read
How to Pass Parameters in URL with Python
Passing parameters in a URL is a common way to send data between a client and a server in web applications. In Python, this is usually done using libraries like requests for making HTTP requests or urllib .Let's understand how to pass parameters in a URL with this example.Example:Pythonimport urllib
2 min read
Timing Functions With Decorators - Python
Everything in Python is an object. Functions in Python also object. Hence, like any other object they can be referenced by variables, stored in data structures like dictionary or list, passed as an argument to another function, and returned as a value from another function. In this article, we are g
4 min read
Decorator Method - Python Design Patterns
Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. It is much easier to implement Decorator Method in Python because of
3 min read
Chain Multiple Decorators in Python
In this article, we will try to understand the basic concept behind how to make function decorators and chain them together we will also try to see Python decorator examples. What is Decorator In Python?A decorator is a function that can take a function as an argument and extend its functionality an
2 min read
Python Function Parameters and Arguments
Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
Python Property Decorator - @property
A decorator feature in Python wraps in a function, appends several functionalities to existing code and then returns it. Methods and functions are known to be callable as they can be called. Therefore, a decorator is also a callable that returns callable. This is also known as metaprogramming as at
3 min read