Python重试函数:如何在调用成功后将attempts重置为0?
问题分析与解决方案
首先你的代码存在两个关键问题:
return func(*args, **kwargs)之后的attempts = 0永远不会执行——return语句会直接退出函数,后续代码根本没机会运行。- 当前用固定20秒等待,没有实现指数退避的核心逻辑(等待时间随尝试次数指数增长)。
针对你“成功时重置attempts为0”的需求,分两种场景给出解决方案:
场景1:每次调用函数时尝试次数从头开始(常规重试逻辑)
这种情况下,每次调用装饰后的函数,尝试次数都会重新从0开始,成功后自然无需额外操作,下次调用还是从头来。同时补上指数退避:
import time def retry(func, retries=5): def retry_wrapper(*args, **kwargs): attempts = 0 while attempts < retries: try: result = func(*args, **kwargs) print(f"调用成功,尝试次数重置为0") return result except Exception as e: print(f'错误 {attempts}: {str(e)}') # 指数退避:等待时间随尝试次数翻倍,可调整基数 wait_time = 2 ** attempts time.sleep(wait_time) attempts += 1 # 重试耗尽仍失败,抛出异常 raise Exception(f"已重试{retries}次,调用仍失败") return retry_wrapper
场景2:尝试次数在多次调用间保持状态(持久化计数)
如果希望尝试次数在多次调用函数时保留(比如第一次调用失败2次,第二次从2开始尝试,成功后再重置为0),把attempts改成闭包变量即可:
import time def retry(func, retries=5): attempts = 0 # 跨调用保持状态的闭包变量 def retry_wrapper(*args, **kwargs): nonlocal attempts while attempts < retries: try: result = func(*args, **kwargs) print(f"调用成功,尝试次数重置为0") attempts = 0 # 成功后手动重置 return result except Exception as e: print(f'错误 {attempts}: {str(e)}') wait_time = 2 ** attempts time.sleep(wait_time) attempts += 1 # 重试耗尽后,可选重置尝试次数,避免后续调用直接跳过 attempts = 0 raise Exception(f"已重试{retries}次,调用仍失败") return retry_wrapper
内容的提问来源于stack exchange,提问作者Andres Martin del Campo
相关产品推荐
相关产品推荐

