defAdvanced Examples

Defines a new function or method

Decorators

Functions that wrap other functions to add behavior.

python
import functools

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        import time
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.6f}s")
        return result
    return wrapper

@timer
def slow_sum(n):
    """Sum numbers from 0 to n."""
    return sum(range(n))

result = slow_sum(1_000_000)
print(f"Result: {result}")
print(f"Docstring preserved: {slow_sum.__doc__}")

Decorators use @syntax to wrap functions. functools.wraps preserves the original function's name and docstring on the wrapper.

Want to try these examples interactively?

Open Advanced Playground