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 lessonWrite 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
- Predict the Decorator OutputIntermediate
- Write a Logging DecoratorAdvanced
- Write a Repeat DecoratorAdvanced
- Predict Stacked Decorator OutputAdvanced
- Write a Validation DecoratorAdvanced
- Fix the Broken DecoratorIntermediate
- Build a Simple Cache DecoratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz