how to count if its the last retry in a function decorated by retrying library in python
The retrying library in Python provides a few options to count the number of retries within a decorated function. One way to count if it's the last retry is to use the retry_on_result parameter along with a custom function that returns True on the last retry.
Here's an example:
import retrying
@retrying.retry(wait_fixed=1000, retry_on_result=lambda result: result is None or result == "retry")
def my_func():
# do something that may fail and return None or "retry"
# ...
# check if it's the last retry
if retrying._retry_state.last_attempt.failed:
print("This is the last retry")
return "success"
In this example, the retry_on_result parameter is set to a lambda function that checks if the result is either None or "retry". This means that the function will be retried if it returns None or "retry".
Inside the function, we check if it's the last retry by accessing the _retry_state attribute of the retrying module and checking the value of the last_attempt attribute. If last_attempt.failed is True, it means that this is the last retry.
Note that accessing _retry_state and last_attempt is not officially documented and may change in future versions of the library
原文地址: https://www.cveoy.top/t/topic/dhqp 著作权归作者所有。请勿转载和采集!