Python, properly · Chapter 31 of 42

Decorators

By the end of this chapter you can read and write decorators: wrap a function to time it, retry it or cache it, without touching its code, and explain what the @ line really does. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Pythonic and typed
  • 4 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

Kunal wants to know which of DabbaDrop's functions are slow. The kitchen printer drops its connection a few times a day, and every function that prints a ticket needs "try again". Rafiq's reports ask the same questions over and over.

You could paste timing code, a retry loop and a dictionary of answers into every function. Then there are twenty copies of each, all slightly different. A decorator writes the extra behaviour once and wraps it around any function with one line. You have used them already (@property, @dataclass); pytest fixtures, web routes and AI tools are all decorators too.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    timed.py: time every call

    Write a decorator timed(func). The function it returns calls func with whatever arguments it was given, prints one line, the function's name, took, the time in whole milliseconds and ms (for example: slow_menu took 51 ms), and returns func's result. It keeps func's name and docstring.

    The check decorates a function that sleeps 50 ms and calls it with a positional and a keyword argument.

  2. Task 2

    retry.py: try again when the connection fails

    Write retry(times), a decorator with an argument, used as @retry(3). The decorated function calls the original and returns its result if it works. If it raises ConnectionError, it calls it again, up to times calls in all; if every call failed, the last ConnectionError is raised. Any other exception is never retried: it goes straight out.

    It passes every argument on and keeps the function's name. The check uses functions that fail twice then work (3 calls), that always fail, and that raise ValueError (1 call).

  3. Task 3 · interview question

    Interview: memoize.py, write your own cache

    Write memoize(func), a decorator, without functools.cache. The first call with some arguments runs func and remembers the result; every later call with the same arguments returns the remembered result without running func again. Positional arguments only. It keeps func's name and docstring.

    The check makes five calls with two different pairs of arguments and counts 2 real calls; a remembered result must be the very same object.

  4. Task 4

    change.py: counting change, fast

    Write ways(amount, coins): how many ways to make amount from the coins (a tuple), where order does not count. The rule: the ways that use the first coin at least once (make amount minus that coin, from the same coins) plus the ways that never use it (make amount from the other coins). An amount of 0 has 1 way; a negative amount, or no coins left, has 0.

    ways(5, (2, 1)) is 3. The check also runs ways(500, (50, 20, 10, 5, 2, 1)) and gives it 3 seconds.

What you will learn

  • Functions are objects: names point at them; you can pass and return them.
  • Writing a decorator by hand, then with @.
  • functools.wraps, and the forgotten return trap.
  • Decorators with arguments, and stacking them.
  • functools.cache: remembering results.

More in Pythonic and typed

Build "Decorators" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.