Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.6 — Decorators
Python · Example 3 of 3

A realistic decorator: timing steps of a pipeline

Timing is the most common decorator in data and AI code. Real code would read time.perf_counter() before and after. Here a fake clock (an iterator from Topic 9.1) gives fixed readings, so the output never changes. Try decorating a third function.

A decorator is a function that takes a function and returns a new one, usually a wrapper that adds behaviour before or after the original. The @name line above a def is shorthand for rebinding the name to the wrapped version.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a decorator shout that upper-cases the string returned by a function. Decorate def greet(name) and print greet("ada").

02

Write a decorator log_result that prints name -> result using the function name and the returned value, and still returns the value. Apply it to a function that multiplies two numbers.

03

Write a decorator count_calls that stores the number of calls in wrapper.calls. Call the decorated function twice and print the count.

Explain it without notes

01

What is a decorator, and what does @decorator above a function mean exactly?

02

Why does a decorator's wrapper use *args, **kwargs, and what happens if it forgets to return the result?

03

What does functools.wraps do and why should every wrapper use it?

04

In what order do stacked decorators apply and run?

05

Describe a retry decorator for a flaky API call. What should it retry, and what should it not?

A realistic decorator: timing steps of a pipeline
Sign in to run this example in your browser.

Expected output

load_data took 0.25 seconds
rows: [1, 2, 3]
train took 2.50 seconds
trained on 3 rows