Advanced Python

Level recap · Advanced Python · Level 2

Functions in depth

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Closures, map, partial, reduce, caching, named-only arguments and decorators with settings.

8 classesLevel exam

Take the level exam
  1. 1A function that remembers: closures

    Inner functions and nonlocal.

    The idea

    Ticket PY-201 from the support desk: each desk needs its own ticket number counter, starting where that desk's numbers start.

    A function defined inside another function can use the outer function's variables, and keeps them after the outer one has finished. That is a closure. To change such a variable, mark it nonlocal inside the inner function. Each call of the outer function makes a new, separate counter.

    The code

    def make_counter(start):
        current = start - 1
        def next_number():
            nonlocal current
            current += 1
            return current
        return next_number
    desk = make_counter(100)
    print(desk(), desk())

    What it shows

    PASS Right on new test values
  2. 2Apply one rule to every item: map

    map with a lambda.

    The idea

    Ticket PY-202 from finance: turn a list of net prices into prices with tax, rounded to cents.

    map(f, items) calls f on every item and gives the results one by one. With a short lambda, map(lambda price: round(price * (1 + tax), 2), prices) applies the tax rule to each price. Wrap it in list(...) to get a list.

    The code

    def with_tax(prices, tax):
        return list(map(lambda price: round(price * (1 + tax), 2), prices))
    print(with_tax([10, 20], 0.14))

    What it shows

    PASS Right on new test values
  3. 3Fix some arguments: partial

    functools.partial.

    The idea

    Ticket PY-203 from HR: staff get 20 percent off. The shop already has apply_discount(price, rate), and the staff page needs a one-argument version.

    partial(f, rate=0.2) makes a new function that calls f with rate=0.2 already filled in. So staff_price = partial(apply_discount, rate=0.2) lets you write staff_price(50). Nothing is copied or rewritten.

    The code

    from functools import partial
    def apply_discount(price, rate):
        return round(price * (1 - rate), 2)
    staff_price = partial(apply_discount, rate=0.2)
    print(staff_price(50))

    What it shows

    PASS Right on new test values
  4. 4Fold a list into one value: reduce

    functools.reduce.

    The idea

    Ticket PY-204 from the warehouse: each warehouse sends a dict of product to units. Head office wants one dict with the total for each product.

    reduce(f, items, start) keeps one running value: it starts with start, then sets it to f(value, item) for each item. With a merge(a, b) that adds two stock dicts, reduce(merge, warehouses, {}) folds every warehouse into one total.

    The code

    from functools import reduce
    def merge(a, b):
        out = dict(a)
        for name, units in b.items():
            out[name] = out.get(name, 0) + units
        return out
    def combine_stock(warehouses):
        return reduce(merge, warehouses, {})
    print(combine_stock([{"Toner": 5}, {"Toner": 2, "Shelf": 1}]))

    What it shows

    PASS Right on new test values
  5. 5Remember answers: lru_cache

    functools.lru_cache.

    The idea

    Ticket PY-205 from the loading dock: a pallet of n boxes is loaded 1, 2 or 3 boxes at a time. Planning wants the number of different loading orders. The plain recursive version never finishes for a big pallet.

    The count for n is ways(n - 1) + ways(n - 2) + ways(n - 3), with ways(0) = 1 and 0 for a negative n. Written plainly, it works out the same smaller answers millions of times. @lru_cache(maxsize=None) above the function stores each answer the first time, so every n is worked out once and big pallets take no time.

    The code

    from functools import lru_cache
    @lru_cache(maxsize=None)
    def ways(n):
        if n < 0:
            return 0
        if n == 0:
            return 1
        return ways(n - 1) + ways(n - 2) + ways(n - 3)
    print(ways(40))

    What it shows

    PASS Right on new test values
  6. 6Arguments that must be named

    Keyword-only arguments with *.

    The idea

    Ticket PY-206 from the engineering lead: someone called format_price(12.5, 0) meaning no decimals, and it printed 0 as the currency. Make the settings impossible to pass by position.

    A bare * in the parameter list means every parameter after it must be given by name. With def format_price(amount, *, currency="USD", decimals=2), format_price(12.5, decimals=0) works and format_price(12.5, "EUR") stops with a TypeError. The call says what each value means.

    The code

    def format_price(amount, *, currency="USD", decimals=2):
        return f"{amount:.{decimals}f} {currency}"
    print(format_price(1234.5, currency="EUR", decimals=1))

    What it shows

    PASS Right on new test values
  7. 7A decorator with settings: retry(times)

    A decorator factory.

    The idea

    Ticket PY-207 from the platform team: calls to the shipping service sometimes fail once or twice, then work. Wrap those calls so they try again, up to a set number of times.

    A decorator with settings is three functions deep. retry(times) gives back decorate(job), which gives back wrapper(*args, kwargs). The wrapper calls job in a loop: if it works, return its answer; if it raises, try again; on the last try, let the error go up with a bare raise. You use it as @retry(3) above any function.

    The code

    def retry(times):
        def decorate(job):
            def wrapper(*args, **kwargs):
                for attempt in range(times):
                    try:
                        return job(*args, **kwargs)
                    except Exception:
                        if attempt == times - 1:
                            raise
            return wrapper
        return decorate
    tries = []
    @retry(3)
    def ship(order_id):
        tries.append(order_id)
        if len(tries) < 3:
            raise ConnectionError("network down")
        return "shipped " + str(order_id)
    …

    What it shows

    PASS Right on new test values
  8. 8On your own: a call log

    A decorator that keeps a record, with no gold line.

    The idea

    Ticket PY-208 from the audit team: for a few sensitive functions, keep a record of every call's arguments, and make sure the wrapped function still shows its own name in error reports. Plan it: where does the list live, and how does the wrapper keep the name?

    In the code box, write a decorator log_calls(func). The wrapper calls func and gives back its answer, adds the call's positional arguments as a tuple to a list wrapper.calls, and keeps func's name with functools.wraps. Then press Run my code.

    The code

    import functools
    def log_calls(func):
        @functools.wraps(func)
        def wrapper(*args):
            wrapper.calls.append(args)
            return func(*args)
        wrapper.calls = []
        return wrapper

    What it shows

    PASS Right on new test values

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam