← Previous Module 10: Advanced Functional Features Next →
Statement
Solution

Python Exercise 10.3: Decorators

Decorators are a powerful Pythonic feature that let you wrap a function to extend its behaviour without modifying its source code. In this exercise, you will build a @timer decorator that measures how long a function takes to execute.

Your program should:

  • Import the time module.
  • Define a timer decorator function that accepts a function func as its argument.
  • Inside timer, define an inner wrapper function that:
    • Records the start time using time.time().
    • Calls the original function and stores its return value.
    • Records the end time and computes elapsed time.
    • Prints the elapsed time in the format: Time taken: X.XXXXXX seconds
    • Returns the original function's return value.
  • Return wrapper from the timer function.
  • Apply the @timer decorator to a function called slow_sum that sums all integers from 1 to 1,000,000 and returns the result.
  • Call slow_sum() and print its return value.

Sample Interaction (Success):

Input
Output
(no input required)
Time taken: 0.045123 seconds 500000500000

Note: The exact elapsed time will vary depending on the machine. Your output just needs to print the time in the correct format followed by the sum on the next line.

Solution

The timer decorator wraps any function using an inner wrapper function. It records timestamps before and after the call to compute elapsed time, then returns the original result unchanged.

import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() elapsed = end - start print(f"Time taken: {elapsed:.6f} seconds") return result return wrapper @timer def slow_sum(): return sum(range(1, 1_000_001)) print(slow_sum())

Key Concepts:

  • A decorator is a function that takes another function as input and returns a new function (the wrapper).
  • @timer above a function definition is syntactic sugar for slow_sum = timer(slow_sum).
  • *args, **kwargs in the wrapper ensures the decorator works with any function signature.
  • time.time() returns the current time as a float of seconds since the epoch; subtracting start from end gives elapsed time.
  • Returning result from wrapper preserves the decorated function's original return value.
  • sum(range(1, 1_000_001)) efficiently sums integers from 1 to 1,000,000 using Python's built-in functions.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top