Fundamentals 5 min read

Using Tenacity: A Python Retry Library – Installation, Unlimited Retries, Stop Conditions, Intervals, and Logging

This article introduces the Tenacity Python library, explains how to install it, and demonstrates various retry strategies such as unlimited retries, stopping after success, limiting attempts or time, combining stop conditions, setting fixed or random wait intervals, and adding pre‑ and post‑retry logging with complete code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Using Tenacity: A Python Retry Library – Installation, Unlimited Retries, Stop Conditions, Intervals, and Logging

Tenacity is an Apache‑2.0 licensed, Python‑based generic retry library that simplifies adding retry behavior to many tasks, such as re‑running test cases, crawling scripts, or ticket‑booking attempts.

Installation pip install Tenacity Unlimited Retry

from tenacity import retry

@retry()
def test_retry():
    print('失败重试中')
    raise Exception

test_retry()

Stop After Success

from tenacity import retry
import random

@retry()
def test_retry():
    if random.randint(0, 10) > 1:
        print('失败重试中')
        raise Exception
    else:
        print('成功')

test_retry()

Limit Number of Attempts

from tenacity import retry, stop_after_attempt
import random

@retry(stop=stop_after_attempt(7))
def test_retry():
    print('失败重试中')
    raise Exception

test_retry()

Limit Total Retry Time

from tenacity import retry, stop_after_delay
import random, time

@retry(stop=stop_after_delay(3))
def test_retry():
    time.sleep(1)
    print('失败重试中')
    raise Exception

test_retry()

Combine Stop Conditions

from tenacity import retry, stop_after_attempt, stop_after_delay
import random, time

@retry(stop=stop_after_delay(3) | stop_after_attempt(2))
def test_retry():
    time.sleep(1)
    print('失败重试中')
    raise Exception

test_retry()

Fixed Retry Interval

from tenacity import retry, wait_fixed
import random, time

@retry(wait=wait_fixed(2))
def test_retry():
    print('失败重试中')
    print(time.ctime())
    raise Exception

test_retry()

Random Retry Interval

from tenacity import retry, wait_random
import random, time

@retry(wait=wait_random(min=1, max=2))
def test_retry():
    print('失败重试中')
    print(time.ctime())
    raise Exception

test_retry()

Log Before Each Retry

from tenacity import retry, stop_after_attempt, before_log
import logging, sys

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
def test_retry():
    print('失败重试中')
    raise Exception('Fail')

test_retry()

Log After Each Retry

from tenacity import retry, stop_after_attempt, after_log
import logging, sys

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3), after=after_log(logger, logging.DEBUG))
def test_retry():
    print('失败重试中')
    raise Exception('Fail')

test_retry()

The article concludes with a disclaimer that the content is collected from the internet and the original author retains copyright.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

loggingRetryexception-handlingBackofftenacitycode-example
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.