root@coding-prodigies:~# โ–Š
// lesson 3 of 12 ยท 18 min

Decorators

โš‘ Report an issue with this lesson
import time

def timed(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.3f}s")
        return result
    return wrapper

@timed
def slow_query():
    time.sleep(1)

A decorator wraps a function with extra behavior without changing its code. @timed is equivalent to writing slow_query = timed(slow_query) โ€” decorators are just a cleaner syntax for that pattern.

Try it yourself

Exercise: Write a @timed decorator that prints how long the wrapped function took.
Expected output: open-ended โ€” there's no single correct output here, just get your code running without errors.
python
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

9 more lessons โ€” including Capstone project: a tested, packaged CLI โ€” plus a certificate are waiting.

Unlock the full course โ€” $149.99