Decorators in Python. Topic – 42

Decorators in Python

Today in this content we will learn about the decorators in Python. They provide a clean and concise way to add functionality to existing code without directly changing its implementation. A decorator is a function that takes another function as an argument and returns a modified version of it. This modified function is called the “decorated function”. The basic syntax of decorator is the following:

def my_function():

Before we learn about decorators, we need to understand about Python functions, class, and objects. Also, remember that everything in Python is an object, even functions are objects. If you know these concepts, then you are good to go. So let’s see into the code.

Suppose I have a normal function that prints something.

def hello():
    print("Jai shree ram!")


So, I had a requirement that I had to print “Welcome to this coding world” before running each function and “Jai hind” at the end. So, in this situation, we can do two things. One is to modify each function. And that would not be a good process. Because we may have 1000 functions. So, in this situation, we can use decorators. Let’s understand through code.

def greet(fx): # Define the decorator function named 'greet' that takes a function as its argument
    def modified_fx():  # Define an inner function 'modified_fx'
        print("Welcome to the coding world.")   # Print a welcome message before the decorated function
        fx() # Call the original function passed as the argument (fx)
        print("Jai Hind") # Print a closing message after the decorated function
    return modified_fx  # Return the modified function

@greet # Apply the decorator 'greet' to the 'hello' function
def hello():
    print("Jai shree ram!") # The original function body of 'hello'

hello()  # Call the decorated 'hello' function

# we can run this function also like this 

Let’s Simplify This Code:

This function takes another function (fx) as its argument. It acts as a wrapper that will modify the behavior of the function it decorates.

  • An inner function modified_fx is defined.
  • modified_fx performs the following actions:
  • Prints a welcome message.
  • Calls the original function passed as the argument (fx()). This is where the decorated function’s actual code (print(“Jai shree ram!”) in this case) gets executed.
  • Prints a closing message.
  • return modified_fx: The inner function (modified_fx) is returned, effectively replacing the original function with the modified behavior.

So, we have understood this through a normal function. Now let’s see how we can do this if we need to pass parameters. Let’s see in the code.

def welcome_decorator(function_to_decorate):  # Clearer decorator name

    def wrapper(*args, **kwargs):  # Handle any number of arguments
        print("Welcome to our awesome calculator!")
        print(function_to_decorate(*args, **kwargs))  # Call original function with arguments
        print("Thank you for using the calculator!")

    return wrapper

@welcome_decorator  # Apply the decorator
def my_calculator(x, y):  # Your original function
    return x + y


Let’s make it simple with a funny example:

Imagine a Party Hat: The decorator is like a party hat we put on a function (my_calculator). It adds some extra things (welcome and goodbye messages) before and after the function does its job (calculation).

Welcome Party: The decorator function (welcome_decorator) makes a wrapper function (wrapper). The wrapper function:

  •   Says “Welcome!” before calling the function with a party hat (function_to_decorate(*args, **kwargs))
  •   Gets the result from the function.
  •   Says “Thank you!” after the function is done.

Putting on the Party Hat: The @welcome_decorator line puts the party hat (decorator) on the my_calculator function.

Party Time!: When you call my_calculator(10, 20), the decorated function with the party hat is called. It calculates the sum (30), says “Welcome!” and “Thank you!”, and gives you the result (30).

Real-life use case of Decorators:

import logging

def log_function_call(func):
    def decorated(*args, **kwargs):"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)"{func.__name__} returned {result}")
        return result
    return decorated

def my_function(a, b):
    return a + b
Constructor in Python

Constructor in Python

Constractor is a special method, that initializes the object of a class. Its name is __init__. When we create a new object, the constructor calls…..

I hope you understand “Decorators in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog