Meaning
A parameterized decorator that executes the decorated function a specified number of times, useful for repeating side‑effects or retry‑like behavior without writing explicit loops.
Primary Function
Higher‑order function / decorator
Communicative Purpose
Encapsulate repetitive execution of a function call in a reusable declarative form.
Pattern
def repeat(;): def decorator(;): def wrapper(*args, **kwargs): for _ in range(;): ;(*args, **kwargs) return wrapper return decorator
Core Structure
def repeat(;): def decorator(;): def wrapper(*args, **kwargs): for _ in range(;): ;(*args, **kwargs) return wrapper return decorator
Função primária
Higher‑order function / decorator
Propósito comunicativo
Encapsulate repetitive execution of a function call in a reusable declarative form.
Situações de gatilho
You need to call the same function multiple times in a row (e.g., polling, retry attempts, stress testing); you want to avoid duplicating a for‑loop at each call site.
Contextos
Found in test utilities, automation scripts, game loops, and any Python codebase that uses decorators for cross‑cutting concerns.
Padrão
def repeat(;): def decorator(;): def wrapper(*args, **kwargs): for _ in range(;): ;(*args, **kwargs) return wrapper return decorator
Estrutura central
def repeat(;): def decorator(;): def wrapper(*args, **kwargs): for _ in range(;): ;(*args, **kwargs) return wrapper return decorator
Slots de substituição
times: integer specifying repetitions; func: the callable to be executed
Colocados típicos
- @repeat(N) above functions with side effects such as logging
- API calls
- or state updates
Substituições comuns
- Writing an explicit for loop
- using functools.partial to bind arguments
- a custom retry decorator that catches exceptions
Erros comuns
Omitting the return wrapper (so the decorated function returns None); misplacing the loop inside the decorator instead of the wrapper; using mutable defaults for times
Similar / contraste
@retry (executes until success or max attempts) – repeats only on failure; @timeout – limits execution duration; @cache – stores results to avoid recomputation
Interferências
Coming from Java: expecting @ syntax similar to annotations; forgetting that Python decorators are just functions that return functions
Família do chunk
- decorator_pattern
Nuance
Only the return value of the final iteration is accessible; earlier results are discarded. If you need to collect results, modify the wrapper to accumulate them. Side effects will occur times times.
Efeito pragmático
Makes repetitive execution explicit, reduces boilerplate, and clarifies intent at the call site.
Dica de memória
Think of a mantra: repeat the action N times.
Nota
Only the return value of the final iteration is returned; earlier results are discarded unless accumulated.
Upgrade path
Can be extended to a retry decorator with exponential backoff or a caching decorator.
Log in to save chunks.