Decorators in Python is a very useful concept as it helps in making a function or class more dynamic.
In decorators, we have wrapper function(inner function) and we are passing one function as an argument to the outer function and which will be called inside the wrapped function.

With the help of examples will try to understand how to create a decorator function.

How to create a decorator

Another way of calling the decorator function

Syntax of decorator –¬†@ function_name/class_name¬†inside which decorated function will be passed

This syntax is declared before the definition of the decorated function.

Function with arguments

Redefining the outer function(a company in our case) in order to handle the multiple arguments

As we are doing all the things with function, similarly we can create decorators using class.
Here, we are not discussing in details using class but it is almost similar as we did for functions.

From the use cases point of view, you might be thinking about what will be uses of decorators.
Here are some of the use cases where decorators can be used but as we get to know that decorators help in making any function/class more dynamic is one of the good use cases.
Let’s see what are some of the use cases -:
1. Logging
2. Time was taken during the execution of the function

We will discuss logging with decorators in upcoming blogs.
Hope you enjoyed learning decorators. Stay tuned for more exciting blogs in intermediate Python. Keep learning!


Close Menu