Decorators in Python are really a very powerful feature. If you are a web developer and you have used the Django framework or even some other development frameworks you would have already come across decorators.
For an overview decorators are wrapper functions that wrap an existing function or a method and modify its features. Let’s take a short example. Consider that you have a speak function that returns a neutral message
Suppose that you need to modify the function to return a message in a happy tone. So let’s create a decorator for this.
Hi, Geeks! You are happy!
Debugging a decorator
In this way, the decorators can also be used to modify different functions and make them more useful. However, there are some drawbacks to this process. When we wrap the original function in a decorator the metadata of the original function gets lost. Consider the below program but this time we use the decorator in another way just to make you understand.
If you try to access any of the metadata of the positive_message function it actually returns the metadata of the wrapper inside the decorator.
Hi! You are happy! speak Returns a neutral message wrapper None
These results make it really very difficult for debugging. But thanks to Python it also has a solution to fix this problem without much effort. We just need to use the functools.wraps() decorator included in the Python standard library.
Here’s an example:
Hi! You are happy! speak Returns a neutral message speak Returns a neutral message
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Function Decorators in Python | Set 1 (Introduction)
- Decorators in Python
- Decorators with parameters in Python
- Memoization using decorators in Python
- Useful cases to illustrate Decorators in python
- Nested Decorators in Python
- Chain Multiple Decorators in Python
- Python Decorators: A Complete Guide
- Conditional Decorators in Python
- Error Handling in Python using Decorators
- Python | Basic Program Crash Debugging
- Debugging Python code using breakpoint() and pdb
- How to preserve Function Metadata while using Decorators?
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.