Editor

Write a Retry Decorator

Advanced · Write the code · 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

Write a decorator retry(max_attempts) that retries a function up to max_attempts times if it raises an exception. Print a message on each retry. If all attempts fail, print the final error.

Test with a counter that fails twice then succeeds:

call_count = 0

@retry(3)
def flaky_function():
    global call_count
    call_count += 1
    if call_count < 3:
        raise ValueError('not ready yet')
    return 'success!'

print(flaky_function())
from functools import wraps
def retry(max_attempts):
# Write your decorator factory here
pass
call_count = 0
@retry(3)
def flaky_function():
global call_count
call_count += 1
if call_count < 3:
raise ValueError('not ready yet')
return 'success!'
print(flaky_function())

More Decorator exercises

All Python exercises · 50 practice problems · Advanced Python quiz