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
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 :
# 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
Output
Inside decorator Inside inner function Decorated the function Inside actual function
Another Way:
# 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)()
Output
Inside 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 parameterlike.inner(func): This function wraps the actual functionfuncand uses the parameterlikewithin its scope.wrapper(): Thewrapperfunction is used to call the actualfunc, and it is returned from theinnerfunction.
# 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()
Output
Inside 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,xandy, and returns a decorator.Inner(func): This is the actual decorator returned bydecorator_func. It takes a functionfuncand defines awrapperfunction around it.wrapper(*args, **kwargs): This function is executed when the decorated function is called. It prints some messages and the summation ofxandybefore calling the original functionfunc.return wrapper: Thewrapperfunction is returned by theInnerfunction.return Inner: TheInnerdecorator is returned bydecorator_func.decorator_func(12, 15)(my_fun)('Geeks', 'for', 'Geeks'): This line applies the decorator with the parameters12and15tomy_fun. The decorator prints the message and summation before callingmy_funwith the arguments'Geeks','for','Geeks'.
# 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')
Output
I like Geeksforgeeks Summation of values - 27 Geeks for Geeks
Example 3:
Here is the code Explaination
- Decorator Function
type_check_decorator:- Parameter:
expected_typespecifies the type that all arguments should be. - Inner Function
decorator: Takes the functionfuncto be decorated. - Wrapper Function
wrapper: Checks if all arguments are ofexpected_typeand callsfuncif they are; otherwise, returns"Invalid Input".
- Parameter:
- 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.
# 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))
Output
I like Geeksforgeeks 1729
1. Inside the Decorator

2. Inside the function

Note: Image snapshots are taken using PythonTutor.