Python’s decorators are a highly strong and practical tool because they let programmers change the behavior of a function or class. Decorators enable us to wrap another function in order to modify its behavior temporarily while extending the behavior of the wrapped function.
For example, now we have a function called hello()
def hello():
print('hello')
We wanted to add more function temporarily. Decorators allow us to switch on and off to the additional function.
Now we create another function called hello_decorator()
def hello_decorator(func):
def wrapper():
print('Before hello function')
func()
print('After hello function')
return wrapper
The hello_decorator() will return the wrapper(). By passing the hello() as an argument and called inside the hello_decorator().
decorated_hello = hello_decorator(hello)
Now we execute decorated_hello(), it will return
Before hello function
hello
After hello function