Skip to content

Function Decorators

Medium ~35 min

What you'll build

Three reusable decorators: @timer (measure execution time), @log_calls (log args and result), and @retry (retry on exception with backoff).

Goals

  • Understand decorators as functions that wrap functions
  • Preserve function metadata with functools.wraps
  • Accept *args and **kwargs for generic wrappers
  • Build a parameterized decorator (retry with args)

Prerequisites

  • Functions and parameters
  • *args and **kwargs
  • try/except exception handling

Steps

  1. 1

    Write a basic timer decorator

    A decorator is a function that takes a function and returns a wrapped version. Start with @timer that measures and prints execution time using time.perf_counter.

    Code
    import time
    from functools import wraps
    
    def timer(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time.perf_counter()
            result = func(*args, **kwargs)
            elapsed = time.perf_counter() - start
            print(f"{func.__name__} took {elapsed:.4f}s")
            return result
        return wrapper
    
    @timer
    def slow_sum(n):
        return sum(range(n))
    
    print(slow_sum(1_000_000))  # prints time, then result

    Expected result

    Calling slow_sum prints the execution time and the result.

  2. 2

    Add a logging decorator

    Write @log_calls that prints the function name, arguments, and return value. Use functools.wraps to preserve the original function's name and docstring.

    Code
    def log_calls(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"Calling {func.__name__}({args}, {kwargs})")
            result = func(*args, **kwargs)
            print(f"{func.__name__} returned {result}")
            return result
        return wrapper
    
    @log_calls
    def greet(name, greeting="Hello"):
        return f"{greeting}, {name}!"
    
    print(greet("Alice", greeting="Hi"))

    Expected result

    Prints the call, the return value, and the final result.

  3. 3

    Write a parameterized retry decorator

    A parameterized decorator takes arguments itself, so it needs three levels of nesting. Write @retry(times=3, delay=0.1) that retries on exception.

    Code
    def retry(times=3, delay=0.1):
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                for attempt in range(times):
                    try:
                        return func(*args, **kwargs)
                    except Exception as e:
                        if attempt == times - 1:
                            raise
                        print(f"Retry {attempt + 1}/{times}: {e}")
                        time.sleep(delay)
            return wrapper
        return decorator
    
    @retry(times=3, delay=0.1)
    def flaky():
        import random
        if random.random() < 0.5:
            raise ValueError("Random fail")
        return "success"
    
    print(flaky())

    Expected result

    Retries up to 3 times; eventually returns 'success' or raises after 3 fails.

  4. 4

    Stack multiple decorators

    Apply @timer, @log_calls, and @retry to the same function. Decorators apply bottom-up, so the order matters. Test which decorator runs first.

    Code
    @timer
    @log_calls
    @retry(times=2)
    def process(data):
        return len(data)
    
    print(process([1, 2, 3]))

    Expected result

    retry wraps process, log_calls wraps retry, timer wraps log_calls — timer measures everything.

  5. 5

    Verify metadata preservation

    Without functools.wraps, the wrapped function's __name__ becomes 'wrapper'. Verify that with @wraps, the name and docstring are preserved.

    Code
    print(slow_sum.__name__)  # 'slow_sum', not 'wrapper'
    print(slow_sum.__doc__)   # original docstring
    
    # Without @wraps it would print 'wrapper'

    Expected result

    __name__ is 'slow_sum', confirming @wraps preserved the metadata.

Try it yourself

What you learned

You built reusable decorators — the pattern behind Flask routes, pytest fixtures, and many Python libraries. Decorators let you add cross-cutting behavior without modifying functions.

Related Resources

Related Lessons

  • Functions

    Decorators are higher-order functions.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic