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.

Python Retry: Counting and Identifying the Last Retry Attempt

原文地址: https://www.cveoy.top/t/topic/nDIy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录