Decorators in Python

Rina Mondal
1 min readMay 5, 2024

--

In Python, decorators are a powerful feature that allows to modify or extend the behavior of functions or methods without directly changing their code. Decorators in Python is a function that receives another function as input and adds some functionality (decoration) to it and returns it. In other words, Decorators are essentially functions that wrap other functions or methods to add some additional functionality.

Example: In the below example try to understand the flow of how decorators works.

def my_decorator(function):
def wrapper():
print("Hey")
function()
print("How can I help?")
return wrapper

def name():
print("I am Peter")

a=my_decorator(name)
a()

# Output:
Hey
I am Peter
How can I help?

Now, the same program is written using the decorator format:

def my_decorator(function):
def wrapper():
print("Hey")
function()
print("How can I help?")
return wrapper

@my_decorator ##this symbol signifies that it is a decorator
def name():
print("I am Peter")

name()

Decorators are commonly used for tasks like logging, authentication, authorization, and memoization, among others. They offer a clean and elegant way to extend the behavior of functions or methods without modifying their original code.

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.