Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Decorators

By the end of this chapter, you'll be able to

  • Explain what a closure is and what nonlocal is for
  • Write a decorator that wraps a function with *args and **kwargs
  • Keep the function's name and documentation with functools.wraps
  • Write a decorator that accepts parameters

Functions are values

In Python, a function is an object like any other: you can store it in a variable, pass it as an argument, return it from another function. A function defined inside another one keeps access to that function's variables, even after it has returned: it's a closure.

def counter():
    total = 0
    def add(n):
        nonlocal total
        total += n
        return total
    return add

till = counter()
till(500)
print(till(250))
other = counter()
print(other(10))
750
10

nonlocal total lets add change the enclosing function's variable (without it, total += n would create a local variable and raise an error). Each call to counter() creates its own closure, with its own total.

Writing a decorator

A decorator is a function that receives a function and returns a new one, which wraps it:

import functools

def log(function):
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        print(f"→ {function.__name__}{args}")
        result = function(*args, **kwargs)
        print(f"← {function.__name__} = {result}")
        return result
    return wrapper

@log
def convert(amount, rate):
    """Converts an amount with an exchange rate."""
    return round(amount * rate, 2)

convert(100, 655.957)
print(convert.__name__, "-", convert.__doc__)
→ convert(100, 655.957)
← convert = 65595.7
convert - Converts an amount with an exchange rate.
  • @log above def convert is a shorthand for convert = log(convert);
  • *args and **kwargs receive all the arguments, positional and named, and pass them on unchanged: the wrapper works with any function;
  • functools.wraps(function) copies the original function's name, documentation and other metadata onto the wrapper.

It returns the result: for the caller, nothing has changed.

Step 5 of 5
Text description of the animation
  1. The name convert now refers to the wrapper, not the original function.
  2. The wrapper runs its own code first: here, it logs the call.
  3. It calls the original function, which it kept in its closure, with the same arguments.
  4. It takes control again after the calculation and logs the result.
  5. It returns the result: for the caller, nothing has changed.

A decorator with parameters

To write @retry(times=3), you need one more level: a function that receives the parameters and returns the decorator.

import functools

def retry(times):
    def decorator(function):
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return function(*args, **kwargs)
                except ConnectionError as error:
                    print(f"Attempt {attempt} failed: {error}")
            raise ConnectionError(f"giving up after {times} attempts")
        return wrapper
    return decorator

responses = iter([ConnectionError("timed out"), ConnectionError("network down"), "200 OK"])

@retry(times=3)
def call_api():
    r = next(responses)
    if isinstance(r, Exception):
        raise r
    return r

print(call_api())
Attempt 1 failed: timed out
Attempt 2 failed: network down
200 OK

Here, call_api simulates an unstable service: its first two calls fail. The decorator retries without the function having to worry about it. In a real program, you'd wait a little between two attempts, longer and longer.

Your turn

Worked exercise

Worked exercise: the validation decorator

Write a decorator check_positive that checks that all of a function's positional arguments are strictly positive numbers. Otherwise, it raises a ValueError naming the function and the faulty argument. Apply it to area(width, height) and test it with (4, 2.5), (3, -1) and (2, "5").

Hint 1
In the wrapper, go through args with a loop before calling the function.
Hint 2
isinstance(a, (int, float)) checks that a value is an integer or a float.
Show the solution and common mistakes
import functools

def check_positive(function):
    @functools.wraps(function)
    def wrapper(*args):
        for a in args:
            if not isinstance(a, (int, float)) or a <= 0:
                raise ValueError(f"{function.__name__}: invalid argument {a!r}")
        return function(*args)
    return wrapper

@check_positive
def area(width, height):
    return width * height

print(area(4, 2.5))
for args in [(3, -1), (2, "5")]:
    try:
        area(*args)
    except ValueError as error:
        print(error)
10.0
area: invalid argument -1
area: invalid argument '5'

area(*args) unpacks the tuple: area(*(3, -1)) is equivalent to area(3, -1).

Common mistakes:

  • Testing a <= 0 before isinstance: comparing "5" <= 0 raises a TypeError instead of the intended message. The order of the conditions matters, because or stops at the first true test.
  • Calling the function before the check: the calculation would already have happened with invalid data.

Summary

  1. 1A closure keeps access to the variables of the function that created it; nonlocal lets you change them.
  2. 2A decorator receives a function and returns a wrapper: @deco is equivalent to f = deco(f).
  3. 3*args and **kwargs pass on all the arguments, whatever the function.
  4. 4functools.wraps keeps the original function's name and documentation.
  5. 5A decorator with parameters is a function that returns a decorator.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.