CLI journal project (3/6): decorators and metrics

Time parse_lines and aggregate, log how many lines you saw, and keep __name__ with functools.wraps. Twelve decorator exercises for the journal CLI.

Illustration : cube turquoise enveloppé d'anneaux translucides flottant au-dessus d'un ordinateur portable, image d'une fonction décorée

AI-generated illustration

Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.

Wrap parse_lines and aggregate with a @timed decorator that records the duration through logging.info or print in debug mode. A second decorator, @log_calls, can count invocations — useful when you want to check that you are not parsing again inside a loop by mistake.

Use functools.wraps so __name__ and the docstring stay intact, and so pytest and help() remain readable.

Previous chapter: parsing with generators.

Exercises (12)

Exercise 1 — A timed decorator with time.perf_counter. Easy

Show the solution
import time, functools, logging
def timed(f):
    @functools.wraps(f)
    def wrapper(*a, **k):
        t0 = time.perf_counter()
        out = f(*a, **k)
        logging.info("%s took %.4fs", f.__name__, time.perf_counter() - t0)
        return out
    return wrapper

Exercise 2 — Apply @timed to aggregate only — why not to the generator without consuming it? Intermediate

Show the solution
# timed on a function that returns a generator measures creation, not the walk.

Exercise 3 — A count_lines decorator on a generator that increments a global Counter — the trap. Hard

Show the solution
# Global state: prefer a class, or a closure with a counter per call.

Exercise 4 — logging.basicConfig(level=logging.DEBUG) in main only. Easy

Show the solution
import logging
logging.basicConfig(level=logging.DEBUG)

Exercise 5 — Test: mock logging.info and check that it is called with timed. Hard

Show the solution
def test_timed_logs(caplog):
    @timed
    def f():
        return 1
    with caplog.at_level(logging.INFO):
        f()
    assert "took" in caplog.text

Exercise 6 — lru_cache on parse_line when the line is alone — is it relevant? Intermediate

Show the solution
# Can help when many lines are duplicates; otherwise it costs memory.

Exercise 7 — singledispatch on the source type — file versus stdin. Hard

Show the solution
# Two parse_lines implementations, one for Path and one for TextIO.

Exercise 8 — Order of the decorators @timed and @log_calls on f. Intermediate

Show the solution
# @timed @log_calls def f → f = timed(log_calls(f)) — log_calls runs first on the call.

Exercise 9 — Avoid side effects in decorators: the principle. Easy

Show the solution
A decorator must not break the signature or the metadata (wraps).

Exercise 10 — A contextmanager to time a block inside main. Intermediate

Show the solution
from contextlib import contextmanager
@contextmanager
def timer(name):
    t0 = time.perf_counter()
    yield
    print(name, time.perf_counter() - t0)

Exercise 11 — __wrapped__ after wraps — what it is for. Hard

Show the solution
# Reach the original decorated function.

Exercise 12 — Document in the README the --verbose flag that turns the decorator logs on. Easy

Show the solution
--verbose: DEBUG level for parse and aggregate durations.

Next

asyncio and a batch of files

Amazon

Check today’s price on Amazon

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.