Chapters
Python114 chapters

Exercises

Decorators

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

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))
Exercise 2

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__)
Exercise 3

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)