Function Wrappers

Carson West

Chaining Decorators

Function Wrappers

Function wrappers are a powerful technique in Python that allows you to extend or modify the behavior of a function without modifying its core functionality. This is achieved by creating a new function that wraps around the original function, executing additional code before or after the original function’s execution.

Key aspects:

def my_wrapper(func):
    def wrapper(*args, **kwargs):
        print("Before function execution")
        result = func(*args, **kwargs)
        print("After function execution")
        return result
    return wrapper

@my_wrapper
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

This will print:

Before function execution
Hello, World!
After function execution
from functools import wraps

def my_wrapper(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # ...wrapper logic...
        return func(*args, **kwargs)
    return wrapper

Without wraps, the decorated function might lose its original name and docstring.

def repeat(num_times):
    def decorator_repeat(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

This example shows a decorator factory repeat that takes num_times as an argument.

Remember to consult the official Python documentation for more advanced details and examples.