run_n_times() Decorator in Python 2026 – Best Practices
The run_n_times() decorator is a practical and commonly used decorator factory that executes a function multiple times. It is excellent for benchmarking, stress testing, retry logic, and running simulations.
TL;DR — What run_n_times() Does
- Takes a number
nas argument - Runs the decorated function
ntimes - Returns the result of the last execution (or a list of all results)
- Preserves original function metadata with
@wraps
1. Complete Implementation
from functools import wraps
from typing import Callable, Any
def run_n_times(n: int = 2):
"""Decorator that runs a function n times."""
if n < 1:
raise ValueError("n must be at least 1")
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
result = None
for i in range(n):
print(f"Running {func.__name__}() - execution {i+1}/{n}")
result = func(*args, **kwargs)
return result # Returns result of the last run
return wrapper
return decorator
2. Usage Examples
@run_n_times(5)
def roll_dice():
import random
return random.randint(1, 6)
print("Final result:", roll_dice())
@run_n_times(3)
def expensive_calculation(x: int):
print(f"Calculating for x = {x}")
return x ** 3
print(expensive_calculation(10))
3. Advanced Version – Return All Results
def run_n_times_collect(n: int = 2):
"""Variant that collects and returns all results."""
def decorator(func: Callable):
@wraps(func)
def wrapper(*args, **kwargs):
results = []
for i in range(n):
result = func(*args, **kwargs)
results.append(result)
return results
return wrapper
return decorator
@run_n_times_collect(4)
def simulate():
import random
return random.random()
print(simulate())
4. Best Practices in 2026
- Use meaningful names like
run_n_timesorrepeat - Always validate the input parameter (
n) - Use
@wrapsto preserve function name and docstring - Decide whether to return the last result or all results based on use case
- Combine with
@timerfor performance benchmarking
Conclusion
The run_n_times() decorator is a clean and reusable tool for repeating function execution. In 2026, it is frequently used for benchmarking, testing reliability, running Monte Carlo simulations, and stress testing. Mastering decorator factories like this one significantly improves your ability to write flexible and powerful Python code.
Next steps:
- Try using
@run_n_times(10)on a function you want to benchmark or stress test - Related articles: Decorators That Take Arguments in Python 2026 • Decorators in Python 2026 • Writing Functions in Python 2026