Write a Repeat Decorator
Advanced · Write the code · from Python Decorators Explained: A Step-by-Step Guide
From the lesson: How Do You Write a Decorator That Takes Arguments?
Sometimes you want to configure a decorator. For example, a @repeat(3) decorator that calls a function 3 times. This requires an extra layer of nesting - a function that returns a decorator.
Read this part of the lessonWrite a decorator repeat(n) that calls the decorated function n times and collects all return values into a list.
@repeat(3)
def roll_dice():
return 6
print(roll_dice())
# Output: [6, 6, 6]from functools import wraps
def repeat(n):
# Write your decorator factory here
pass
@repeat(3)
def roll_dice():
return 6
print(roll_dice())
More Decorator exercises
- Predict the Decorator OutputIntermediate
- Write a Logging DecoratorAdvanced
- Predict Stacked Decorator OutputAdvanced
- Write a Validation DecoratorAdvanced
- Write a Retry DecoratorAdvanced
- Fix the Broken DecoratorIntermediate
- Build a Simple Cache DecoratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz