In Python, functions are the first class objects, which means that –
- Functions are objects; they can be referenced to, passed to a variable and returned from other functions as well.
- Functions can be defined inside another function and can also be passed as argument to another function.
Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it.
In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
Syntax for Decorator:
In the above code,
gfg_decorator is a callable function, will add some code on the top of some another callable function,
hello_decorator function and return the wrapper function.
Decorator can modify the behavior:
Hello, this is before function execution This is inside the function !! This is after function execution
Let’s see the behavior of the above code how it runs step by step when the “function_to_be_used” is called.
Let’s jump to another example where we can easily find out the execution time of a function using a decorator.
3628800 Total time taken in : factorial 2.0061802864074707
What if a function returns something –
In all the above examples the functions didn’t return anything so there wasn’t any issue, but one may need the returned value.
before Execution Inside the function after Execution Sum = 3
- Conditional Decorators in Python
- Decorators with parameters in Python
- Nested Decorators in Python
- Memoization using decorators in Python
- Python Decorators: A Complete Guide
- Function Decorators in Python | Set 1 (Introduction)
- Chain Multiple Decorators in Python
- Useful cases to illustrate Decorators in python
- How to preserve Function Metadata while using Decorators?
- Python - Read blob object in python using wand library
- MySQL-Connector-Python module in Python
- Important differences between Python 2.x and Python 3.x with examples
- Reading Python File-Like Objects from C | Python
- Python | Convert list to Python array
- Python | Index of Non-Zero elements in Python list
- Python | PRAW - Python Reddit API Wrapper
- twitter-text-python (ttp) module - Python
- Python | Merge Python key values to list
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
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.