Editor

Fix the Broken Decorator

Intermediate · Fix the bug · from Python Decorators Explained: A Step-by-Step Guide

From the lesson: What Are the Most Useful Real-World Decorators?

Decorators shine in real-world applications. Here are three patterns you'll see constantly: timing, caching, and validation.

Read this part of the lesson

This decorator is supposed to count how many times a function is called. But it has two bugs. Find and fix them.

def count_calls(func):
    count = 0
    def wrapper(*args, **kwargs):
        count += 1
        print(f'Call {count} of {func.__name__}')
        return func(*args, **kwargs)
    return wrapper

@count_calls
def hello():
    print('hello!')

hello()
hello()
hello()
def count_calls(func):
count = 0
def wrapper(*args, **kwargs):
count += 1 # Bug: can't modify outer variable without nonlocal
print(f'Call {count} of {func.__name__}')
return func(*args, **kwargs)
return wrapper
@count_calls
def hello():
print('hello!')
hello()
hello()
hello()

More Decorator exercises

All Python exercises · 50 practice problems · Advanced Python quiz