Python Retry: How to Detect Last Retry Attempt with 'retrying' Library
The 'retrying' library in Python doesn't provide a direct way to check if a retry is the last one. However, you can achieve this by using the 'stop_max_attempt_number' parameter in the 'retrying' decorator.
You can set the 'stop_max_attempt_number' parameter to the maximum number of retries you want to perform, and then use a counter variable to keep track of the number of retries that have been performed. When the counter reaches the maximum number of retries, you can assume that it's the last retry.
Here's an example:
import retrying
@retrying.retry(stop_max_attempt_number=3)
def my_function():
if some_condition:
# raise an exception to trigger a retry
raise Exception('Something went wrong')
# do something
# keep track of the number of retries
retry_count = 0
try:
my_function()
except Exception:
retry_count += 1
if retry_count == 3:
# this is the last retry
print('Last retry')
else:
# there are more retries remaining
print('Retrying...')
In this example, the 'my_function' function is decorated with the 'retrying' decorator with a maximum of 3 retries. When the function raises an exception, the decorator will automatically retry the function up to 3 times.
In the 'try' block, we call the 'my_function' function and catch any exceptions that are raised. We increment the 'retry_count' variable each time the function is retried, and when the 'retry_count' reaches 3, we assume that it's the last retry and print a message. If there are more retries remaining, we print a message indicating that the function is being retried.
原文地址: https://www.cveoy.top/t/topic/nDIo 著作权归作者所有。请勿转载和采集!