Function Wrappers in Python
Wrappers around the functions are also knows as decorators which are a 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 the wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
@wrapper def function(n): statements(s)
This is also similar to
def function(n): statement(s) function = wrapper(function)
Let’s see the below examples for better understanding.
Hello, this is before function execution This is inside the function !! This is after function execution
Example 2: Let’s define a decorator that count the time taken by the function for execution.
countdown 1.6689300537109375e-06 countdown 5.507469177246094e-05
It’s critical to emphasize that decorators generally do not alter the calling signature or return value of function being wrapped. The use of *args and**kwargs is there to make sure that any input arguments can be accepted. The return value of a decorator is almost always the result of calling func(*args, **kwargs), where func is the original unwrapped function.
Please refer Decorators in Python for more details.
Please Login to comment...