Open In App

Decorators with parameters in Python

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Decorators in Python, Function Decorators

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 

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


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)()


Output: 

Inside decorator
Inside inner function
Decorated the function
Inside actual function

  
Let’s move to another example:
 

Example #1: 

Python3




# Python code to illustrate
# Decorators with parameters in Python
 
def decorator(*args, **kwargs):
    print("Inside decorator")
     
    def inner(func):
         
        # code functionality here
        print("Inside inner function")
        print("I like", kwargs['like'])
         
        func()
         
    # returning inner function   
    return inner
 
@decorator(like = "geeksforgeeks")
def my_func():
    print("Inside actual function")


Output: 
 

Inside decorator
Inside inner function
I like geeksforgeeks
Inside actual function

Example #2: 
 

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')


Output:  

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. 
 

Example #3:  

Python3




# Python code to illustrate
# Decorators with parameters in Python  (Multi-level Decorators)
 
 
def decodecorator(dataType, message1, message2):
    def decorator(fun):
        print(message1)
        def wrapper(*args, **kwargs):
            print(message2)
            if all([type(arg) == dataType for arg in args]):
                return fun(*args, **kwargs)
            return "Invalid Input"
        return wrapper
    return decorator
 
 
@decodecorator(str, "Decorator for 'stringJoin'", "stringJoin started ...")
def stringJoin(*args):
    st = ''
    for i in args:
        st += i
    return st
 
 
@decodecorator(int, "Decorator for 'summation'\n", "summation started ...")
def summation(*args):
    summ = 0
    for arg in args:
        summ += arg
    return summ
 
 
print(stringJoin("I ", 'like ', "Geeks", 'for', "geeks"))
print()
print(summation(19, 2, 8, 533, 67, 981, 119))


Output:  

Decorator for 'stringJoin'
Decorator for 'summation'

stringJoin started ...
I like Geeksforgeeks

summation started ...
1729

1. Inside the Decorator

 

inside-the-decorator-python

 

2. Inside the function

 

inside-function-decorator-python

Note: Image snapshots are taken using PythonTutor.
 



Similar Reads

Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Decorators in Python
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it. But before diving deep into decorators let us understand some concepts that will
6 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 calculation of fibonacci series, factorial, etc. But the issue with them is that in the recursion tree, there can be chances that the sub-problem that is already solved is being solved a
3 min read
Useful cases to illustrate Decorators in python
A decorator is a special kind of function that either takes a function and returns a function or takes a class and returns a class. Well, it can be any callable (i.e functions, classes, methods as they can be called) and it can return anything, it can also take a method. This is also called metaprogramming, as a part of the program tries to modify
4 min read
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. Nesting means placing or storing inside the other. Th
2 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 and return a modified function with extended functio
2 min read
Python Decorators: A Complete Guide
A decorator is a design pattern tool in Python for wrapping code around functions or classes (defined blocks). This design pattern allows a programmer to add new functionality to existing functions or classes without modifying the existing structure. The section provides an overview of what decorators are, how to decorate functions and classes, and
9 min read
Conditional Decorators in Python
In Python, decorators are functions or classes that wrap around a function as a wrapper by taking a function as input and returning out a callable. They allow the creation of reusable building code blocks that can either change or extend behavior of other functions. Conditional Decorators Given a condition, the idea here is to execute code or basic
2 min read
Debugging decorators in Python
Decorators in Python are really a very powerful feature. If you are a web developer and you have used the Django framework or even some other development frameworks you would have already come across decorators. For an overview decorators are wrapper functions that wrap an existing function or a method and modify its features. Let's take a short ex
3 min read
Error Handling in Python using Decorators
Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: C/C++ Code # defining decorator function def decorator_example(func): print("Decorator called") # defining inner decorator function def
2 min read
Article Tags :
Practice Tags :