Projects/decorator_exercise.py

33 lines
1.5 KiB
Python

import time
# Step 2: Define the decorator
def time_it(func):
def wrapper(*args, **kwargs):
start_time = time.time() # Start time
result = func(*args, **kwargs) # Call the function
end_time = time.time() # End time
print(f"{func.__name__} took {end_time - start_time} seconds")
return result
return wrapper
# Step 4: Apply the decorator
@time_it
def factorial(n):
"""Function to compute factorial of a number"""
return 1 if n == 0 else n * factorial(n - 1)
# Step 5: Test the decorator
print(factorial(2)) # Replace with any number to test
''' How this code works:
This code defines a decorator indicate and three functions avg_two, avg_three, and avg_many_kwargs , each decorated with indicate. Here's a brief description of each component:
Decorator time_it(func) function:
- Adds functionality to factorial to calculate the difference between the time before and after executing function factorial.
- wrapper takes arguments *args and **kwargs and passes them to the func call (factorial).
- The *args allows the wrapper() function to accept any number of positional arguments as a tuple.
- The **kwargs allows the wrapper() function to accept any number of keyword arguments as a dictionary.
The @time_it decorator is applied to the function:
- factorial(n): Computes the factorial of a number, with timing information displayed due to the decorator.
- The decorator prints the time taken to execute the factorial function.
'''