DECORATORS in python
Nimra Iman
Aspiring Data Scientist | Passionate about ML and AI | Python Developer | Statistical Data Analyst
A decorator is a function that takes another function and makes some changes to it before returning it.
Imagine you have a bunch of functions, and you want to add some common functionality to all of them, like printing a greeting before they start and a thank-you message after they finish. Instead of editing each function individually, which would be a pain especially if you have a lot of functions, decorators allow you to apply this extra behavior to multiple functions easily. So, decorators save your time and make your code cleaner and more organized.
The syntax is to write "@name_of_decorator" before the function that you want to decorate.
In the above code, @greet is a decorator syntax. It's a way of saying that the function below it (helo in this case) should be passed to the greet function.
In the greet function, a function is passed as an argument that we want to decorate. In this case, non_edited_fun is a helo() function. Inside, a new function named edited_fun is defined. This new function adds some extra functionality before and after calling the original function (non_edited_fun).
Inside edited_fun, "good morning" is printed, then the original function (non_edited_fun) is called, and finally "thanks for using" is printed.
The edited_fun function is returned from the greet function. When helo() is called, it actually executes the edited_fun returned by the greet function.
领英推荐
So the actual output is that, first of all, "good morning" is printed then the non_edited_fun() which in this case is the helo() function, and after that "thanks for using" will be printed.
If I don't write @greet before defining the helo function, I can also do it like this:
So far, what we've done is for functions that don't have any arguments. But if there are arguments, here's how to do it.
to avoid any type of error, it is a good practice to write both *args and *kwargs there because the decorator is mostly used to decorate multiple functions, and in some functions, we have passed positional arguments and in some, we have passed keyword arguments.
Hence, the decorator allows you to easily add common functionality to multiple functions without modifying each function individually. It promotes code reusability and helps keep the codebase clean and organized.