gpt4 book ai didi

python - 来自韧性模块的 "Retry"不适用于生成器

转载 作者:行者123 更新时间:2023-12-04 15:32:52 52 4
gpt4 key购买 nike

我在使用 python3 中 tenacity 库中的“重试”工具时遇到问题。当我使用生成器时,“重试”装饰器似乎不起作用。

我有一个代码示例来说明我的情况:

from tenacity import retry, wait_exponential

@retry(wait=wait_exponential(multiplier=1, min=1, max=1))
def test_retry():
print("test retry from tenacity")
for i in range(10):
if i == 0: raise Exception
yield i

def gen():
yield from test_retry()

bar = gen()
for foo in bar:
print(foo)

当它引发异常时,它不会重试。有人知道为什么这不起作用吗?

谢谢

最佳答案

这是 Tenacity 本身的错误/功能/泥潭,其中重试逻辑在生成器函数上失败。 Tenacity 开发人员表示这是因为 "generators use exceptions internally."原始开发人员进一步写道 "tenacity.retry() wrapped the generator function, not the generator itself (i.e. the user's code)."基本上看起来没有任何解决此行为的计划,即使它可以做到。

为了解决这个问题,应将 Tenacity 注释添加到调用生成器的方法中——当异常在调用堆栈中冒泡时,Tenacity 可以很容易地捕获异常。 重要:生成器函数也不能隐藏异常。

# in generator do this and add retry annotations to calling method
...
try:
do_something()
except Exception as ex:
log_or_do_something_else()
raise
finally:
cleanup()
yield something
...


# in generator don't do this
...
try:
do_something()
except Exception as ex:
pass
yield something
...

关于python - 来自韧性模块的 "Retry"不适用于生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60838665/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com