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
timemodule. - Define a
timerdecorator function that accepts a functionfuncas its argument. - Inside
timer, define an innerwrapperfunction 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.
- Records the start time using
- Return
wrapperfrom thetimerfunction. - Apply the
@timerdecorator to a function calledslow_sumthat sums all integers from 1 to 1,000,000 and returns the result. - Call
slow_sum()and print its return value.
Sample Interaction (Success):
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.
Key Concepts:
- A decorator is a function that takes another function as input and returns a new function (the wrapper).
@timerabove a function definition is syntactic sugar forslow_sum = timer(slow_sum).*args, **kwargsin 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
resultfromwrapperpreserves 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.