Exercises
Decorators
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write a decorator that prints before and after the call.
Python
# define loud
@loud
def add(a, b):
return a + b
print(add(2, 3))It takes a function and returns a wrapper that accepts *args and **kwargs.
def loud(fn):
def wrapper(*args, **kwargs):
print("before")
result = fn(*args, **kwargs)
print("after")
return result
return wrapper
@loud
def add(a, b):
return a + b
print(add(2, 3))Exercise 2Passed
The decorator hides the function's name. Fix it so add.__name__ is still add.
Python
def loud(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
@loud
def add(a, b):
"""Add two numbers."""
return a + b
print(add.__name__)
print(add.__doc__)functools has a decorator for decorating wrappers.
from functools import wraps
def loud(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
@loud
def add(a, b):
"""Add two numbers."""
return a + b
print(add.__name__)
print(add.__doc__)Exercise 3Passed
Cache the results so the second call does not recompute.
Python
calls = 0
def square(n):
global calls
calls += 1
return n * n
print(square(4), square(4))
print("calls:", calls)functools.lru_cache is a decorator.
from functools import lru_cache
calls = 0
@lru_cache
def square(n):
global calls
calls += 1
return n * n
print(square(4), square(4))
print("calls:", calls)