Open In App

Chain Multiple Decorators in Python

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 functionality.

So, here in this post, we are going to learn about Decorator Chaining. Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python. we will also see Python decorator examples.

Syntax of decorator in python

@decor1
@decor
def num():
statement(s)

Example 1: 

For num() function we are applying 2 decorator functions. Firstly the inner decorator will work and then the outer decorator.

Python
# code for testing decorator chaining
def decor1(func):
    def inner():
        x = func()
        return x * x
    return inner

def decor(func):
    def inner():
        x = func()
        return 2 * x
    return inner

@decor1
@decor
def num():
    return 10

print(num())

Output:

400

Example 2:

For sayhellogfg() and saygfg function, we are applying 2 decorator functions. Firstly the inner decorator(decor1) will work and then the outer decorator(decor2), and after that, the function datawill be printed.

Python
        
def decor1(func):
        def wrap():
               print("************")
               func()
               print("************")
        return wrap
def decor2(func):
        def wrap():
               print("@@@@@@@@@@@@")
               func()
               print("@@@@@@@@@@@@")
        return wrap
    
@decor1
       
@decor2
def sayhellogfg():
         print("Hello")
def saygfg():
         print("GeekforGeeks")
        
sayhellogfg()
saygfg()

Output:

************
@@@@@@@@@@@@
Hello
@@@@@@@@@@@@
************
GeekforGeeks

You can also learn about Generator in Python.



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
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
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
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 going to see the timing function with decorators. D
4 min read
How to use Function Decorators in Python ?
In Python, a function can be passed as a parameter to another function (a function can also return another function). we can define a function inside another function. In this article, you will learn How to use Function Decorators in Python. Passing Function as ParametersIn Python, you can pass a function as an argument to another function, just li
3 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
7 min read
Closures And Decorators In Python
Closures and decorators are powerful features in Python that allow for more advanced and flexible code patterns. Understanding these concepts can greatly enhance your ability to write clean, efficient, and reusable code. Why Python decorators rather than closures?Python decorators are preferred over closures for their readability, reusability, and
3 min read
Decorators with parameters in Python
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 me
5 min read
How to preserve Function Metadata while using Decorators?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.Note: For more information, refer Decorators in Python How to preserve Metadata? This
2 min read
Chain multiple statements within Psycopg2
In this tutorial, we will see how to chain multiple statements with psycopg2 which is a PostgreSQL database adapter for Python. Chaining is supported by most SQL databases and can be used in various types of SQL clients, such as command-line interfaces, web-based management interfaces, and programming language libraries like psycopg2. let's underst
8 min read
Python - Itertools.chain()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is chain().Note: For more information, refer to Python Itertools chain() function It is a function that takes a series of iterables and r
4 min read
Python - Itertools.chain.from_iterable()
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools The functions under itertools can be classified into
2 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
Chain Code for 2D Line
Chain code is a lossless compression technique used for representing an object in images. The co-ordinates of any continuous boundary of an object can be represented as a string of numbers where each number represents a particular direction in which the next point on the connected line is present. One point is taken as the reference/starting point
12 min read
PyQt5 QSpinBox - Getting next widget in focus chain
In this article we will see how we can get the next in focus chain widget of the spin box. Spin box consist of two child widgets one is line edit and other one is the arrow buttons. Focus is set widget by widget i.e focus chain there fore when spin box get focus its one child get focus before the another child. In order to do this we use nextInFocu
2 min read
PyQt5 QSpinBox - Getting previous widget in focus chain
In this article we will see how we can get the widget which is previous in focus chain of the spin box. Spin box consist of two child widgets one is line edit and other one is the arrow buttons. Focus is set widget by widget i.e focus chain therefore when spin box get focus its one child get focus before the another child similarly before spin box,
2 min read
PyQt5 QCalendarWidget - Getting next widget in focus chain
In this article we will see how we can get the next widget in the focus chain of QCalendarWidget. Focus chain is the list of widgets/children present in the window, they tell the sequence of focus, first item in the focus chain will receive focus first. In order to do this we will use nextInFocusChain method with the QCalendarWidget object. Syntax
2 min read
PyQt5 QCalendarWidget - Getting previous widget in focus chain
In this article we will see how we can get the previous widget in the focus chain of QCalendarWidget. Focus chain is the list of widgets/children present in the window, they tell the sequence of focus, first item in the focus chain will receive focus first. In order to do this we will use previousInFocusChain method with the QCalendarWidget object.
2 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Break a long line into multiple lines in Python
Break a long line into multiple lines, in Python, is very important sometime for enhancing the readability of the code. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex. Example: Breaking a long line of Python code into multiple lines Long Line: a = 1 + 2 + 3 + 4 - 5 * 2
4 min read
Python | Write multiple files data to master file
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file. Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having
2 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Opening multiple color windows to capture using OpenCV in Python
OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
2 min read
Python Program to Convert a list of multiple integers into a single integer
Given a list of integers, write a Python program to convert the given list into a single integer. Examples: Input : [1, 2, 3] Output : 123 Input : [55, 32, 890] Output : 5532890 There are multiple approaches possible to convert the given list into a single integer. Let's see each one by one. Approach #1 : Naive Method Simply iterate each element in
4 min read
Python | Check if given multiple keys exist in a dictionary
A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "
3 min read
Article Tags :
Practice Tags :