Following are important facts about functions in Python that are useful to understand decorator functions.
- In Python, we can define a function inside another function.
- In Python, a function can be passed as parameter to another function (a function can also return another function).
Welcome to GeeksforGeeks
A decorator is a function that takes a function as its only parameter and returns a function. This is helpful to “wrap” functionality with the same code over and over again. For example, above code can be re-written as following.
We use @func_name to specify a decorator to be applied on another function.
Welcome to GeeksforGeeks
Decorators can also be useful to attach data (or add attribute) to functions.
‘add()’ returns sum of x and y passed as arguments but it is wrapped by a decorator function, calling add(2, 3) would simply give sum of two numbers but when we call add.data then ‘add’ function is passed into then decorator function ‘attach_data’ as argument and this function returns ‘add’ function with an attribute ‘data’ that is set to 3 and hence prints it.
Python decorators are a powerful tool to remove redundancy.
Please refer Decorators in Python for more details.
This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
- How to preserve Function Metadata while using Decorators?
- 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
- Debugging decorators in Python
- Error Handling in Python using Decorators
- Complex Numbers in Python | Set 1 (Introduction)
- NumPy in Python | Set 1 (Introduction)
- Multiprocessing in Python | Set 1 (Introduction)
- Array in Python | Set 1 (Introduction and Functions)
- Django Introduction | Set 2 (Creating a Project)
- Python Language Introduction
- Introduction to Kivy ; A Cross-platform Python Framework
- Python | Introduction to Matplotlib
- Introduction to Convolutions using Python