We all have habits of doing some tasks every day since these tasks are repeated every day, and we often find shortcuts to minimise the effort. This is very common behaviour among humans. In programming, when some parts of code are repetitive and lengthy then we also use tools of programing language to save effort.
What are Decorators?
In Python, Decorators are a type of function that takes another function as a parameter and add some functionality to it and then returns it. This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time.
When to use Decorators?
Decorators in Python are used when many functions have some processes similar to each other which make code lengthy and confusing to read. In this case, we create a function or class with a similar process and then use this function as a wrapper to give functionality to another function.
Pros of Decorators in Python
- Decorators save time and minimize the code length.
- Decorators modify the behaviour of the function at compile time.
- Decorators help in creating reusable code and validation checking.
Cons of Decorators in Python
- You need to create code that extends the main code.
- Decorators aren't easy at first but it is not rocket science.
- Decorators are not re-usable/adaptable to other class methods.
- You end up with different objects and comparison is a bit more complex.
To use decorators in python and learn more about decorators, please use resources.