Meaning
The @retry decorator automatically re-executes a function when it raises an exception, allowing a configurable number of attempts and delay between retries. It addresses the pain point of transient failures in external calls, such as network glitches or service throttling, which often resolve on retry. Developers reach for this chunk when wrapping unreliable I/O operations, API clients, or any function that may fail intermittently but succeed on subsequent tries.
Primary Function
Error handling
Communicative Purpose
Ensures automatic retry of failed operations
Pattern
@retry(tries=attempts, delay=delay)
Core Structure
@retry
Função primária
Error handling
Propósito comunicativo
Ensures automatic retry of failed operations
Situações de gatilho
Web API client: handling transient network errors Database access: retrying on deadlock or timeout Cloud function: retrying on throttling errors
Contextos
Python applications using retry libraries such as tenacity, microservices, distributed systems
Padrão
@retry(tries=attempts, delay=delay)
Estrutura central
@retry
Slots de substituição
attempts: int >= 1, delay: float >= 0
Colocados típicos
- exponential backoff
- jitter
- circuit breaker
- timeout handling
Substituições comuns
- Manual retry loop: more control but verbose
- using tenacity's @retry: concise but adds dependency
Erros comuns
Forgetting to import the retry decorator -> NameError Setting tries=0 -> no retries occur Using delay as integer causing insufficient granularity for short waits Retrying non-idempotent operations -> unintended side effects Catching overly broad exceptions -> retrying on programming errors
Similar / contraste
circuit breaker: stops requests after repeated failures vs retry attempts timeout: aborts after a duration vs retrying fallback: provides alternative value vs retrying
Interferências
Coming from Java: may use try-catch loop for retries -> Python's decorator abstracts retry logic Coming from Go: may use manual retry loops -> decorator provides reusable concern
Família do chunk
- @circuit_breaker
- @timeout
- @fallback
Nuance
Do not use for non-idempotent operations where retries could cause duplicate actions Adds latency proportional to attempts × delay; consider exponential backoff to reduce load Boundary: if all attempts fail, the last exception is propagated; ensure callers handle it
Efeito pragmático
Increases resilience of external service calls, reducing failure rates due to transient errors
Dica de memória
Like a phone operator who automatically redials when the line is busy
Upgrade path
Learn advanced retry policies such as exponential backoff with jitter or circuit breaker patterns
Log in to save chunks.