Implementing Wrapper Functions
Basic Wrapper Function
Here's a simple example of a basic wrapper function in Python:
def uppercase_wrapper(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase_wrapper
def greet(name):
return f"Hello, {name}!"
print(greet("LabEx")) ## Output: HELLO, LABEX!
In this example, the uppercase_wrapper
function is a wrapper function that takes a func
argument and returns a new function wrapper
. The wrapper
function calls the original func
and then converts the result to uppercase before returning it.
The @uppercase_wrapper
syntax is a shorthand for applying the wrapper function to the greet
function. This is equivalent to writing greet = uppercase_wrapper(greet)
.
Parameterized Wrapper Functions
Wrapper functions can also accept arguments, allowing you to customize their behavior. Here's an example of a parameterized wrapper function:
def repeat_wrapper(n):
def wrapper(func):
def inner(*args, **kwargs):
result = func(*args, **kwargs)
return result * n
return inner
return wrapper
@repeat_wrapper(3)
def say_hello(name):
return f"Hello, {name}!"
print(say_hello("LabEx")) ## Output: Hello, LabEx!Hello, LabEx!Hello, LabEx!
In this example, the repeat_wrapper
function is a higher-order function that takes an argument n
and returns a new wrapper function. The returned wrapper function then wraps the original func
and repeats the result n
times.
The @repeat_wrapper(3)
syntax applies the repeat_wrapper
with an argument of 3
to the say_hello
function.
Stacking Wrapper Functions
You can also stack multiple wrapper functions on a single function, allowing you to apply multiple layers of functionality:
def uppercase_wrapper(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
def repeat_wrapper(n):
def wrapper(func):
def inner(*args, **kwargs):
result = func(*args, **kwargs)
return result * n
return inner
return wrapper
@uppercase_wrapper
@repeat_wrapper(3)
def say_hello(name):
return f"Hello, {name}!"
print(say_hello("LabEx")) ## Output: HELLO, LABEX!HELLO, LABEX!HELLO, LABEX!
In this example, the say_hello
function is first wrapped by the repeat_wrapper
and then by the uppercase_wrapper
. The order of the wrapper functions matters, as they are applied from the innermost to the outermost.
By understanding the implementation of wrapper functions, you can create powerful and flexible Python code that enhances the behavior of your functions without modifying their core logic.