What are Python Decorators?

This is different from my usual blogs. It's just a short and simple introduction to decorators in Python:
Decorators in Python are just like they sound. We take a function, pass it to a decorator, and it adds something, like a feature or extra functionality, as needed. For example:
# A simple decorator function
def sprinkle_decorator(func):
def wrapper():
print("Sprinkles have been added")
func()
return wrapper
# Applying the decorator to a function
@sprinkle_decorator
def icecream():
print("here is your icecream")
icecream()
As you can see here, we have a function called icecream
, and we want to decorate it with sprinkles. So, we use a decorator, sprinkle_decorator
, which contains a wrapper function. The way a wrapper function works is that the main decorator has a return <wrapper_function>
statement. This essentially calls the wrapper, which then runs the function we need, in this case, icecream()
.
Now, if I want to pass parameters to the function, we use *args
and **kwargs
. The *
in args
allows us to pass any number of parameters as tuples, and the **
in kwargs
allows us to pass them as a dictionary. For example:
def demo(*numbers, **info):
print(numbers)
print(info)
demo(1, 2, 3, name="Sidh", mood="curious")
gives o/p as:
(1, 2, 3)
{'name': 'Sidh', 'mood': 'curious'}
so with our decorator, we can use it as:
# A simple decorator function
def sprinkle_decorator(func):
def wrapper(*args,**kwargs):
print("Sprinkles have been added")
func(*args,**kwargs)
return wrapper
# Applying the decorator to a function
@sprinkle_decorator
def greet(flavour):
print(f"Hers is your {flavour} icecream")
greet("chocolate")
I hope you all enjoyed and understood decorators in this example. I'll see you in the next one!
Subscribe to my newsletter
Read articles from Sidharth Sunu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
