What are Python Decorators?🚀

One of the most frequently asked Python interview questions, Decorators can be a bit tricky to understand, but are highly useful.:bulb:

In simplest terms, a Decorator is a function which takes in another function as an argument to add some more functionality to it.

Let’s take a quick look at the code in the image.

Here the function I_am_decorated() is decorated with another function my_decorator().

What this essentially means is passing the function to the decorator as a wrapper over it:

my_decorator(I_am_decorated)

And there can be multiple decorators. Such as:

dec1( dec2( func ))

So, the decorators are placed using the @ character above the function definition.

@dec1
@dec2
def func():
pass

But what’s their use?:bulb:

Having decorators is very crucial for applications where you need to have different functions with a functionality such as logging details, runtime validations, etc.

Adding all this functionality in every function wouldn’t be the right way, and Decorators make the code more “Pythonic”.

Also, if you have ever seen any code of Flask, it uses “@app.route” decorator to route the control at a specific URL to the function defined below it.:rocket:

What other uses of Decorators do you know?

#python #datascience #machinelearning