Counter
You're working on a new web app, and you are curious about how many times each of the functions in it gets called. So you decide to write a decorator that adds a counter to each function that you decorate. You could use this information in the future to determine whether there are sections of code that you could remove because they are no longer being used by the app.
This exercise is part of the course
Writing Functions in Python
Exercise instructions
- Call the function being decorated and return the result.
- Return the new decorated function.
- Decorate
foo()
with thecounter()
decorator.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return ____
# Set count to 0 to initialize call count for each new decorated function
wrapper.count = 0
# Return the new decorated function
____
# Decorate foo() with the counter() decorator
____
def foo():
print('calling foo()')
foo()
foo()
print('foo() was called {} times.'.format(foo.count))