run_n_times() Decorator in Python 2026

Writing Functions Mar 16, 2026

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 n as argument
  • Runs the decorated function n times
  • 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_times or repeat
  • Always validate the input parameter (n)
  • Use @wraps to preserve function name and docstring
  • Decide whether to return the last result or all results based on use case
  • Combine with @timer for 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:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices