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

标签 python python-3.x generator retry-logic python-tenacity

我在使用 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/

相关文章:

Python pandas - 未实现多索引上多级重叠的合并

从 cronjob 运行时,Python 找不到自定义安装的模块

python-3.x - python 3 pyinstaller 始终给出 "failed to create process"

python - 多个gpus(1080Ti)在tensorflow中不加速训练,在cifar10_estimator代码上测试

node.js - Node.js 流可以做成协程吗?

python - 如何从 3d NumPy 数组绘制单个像素值?

python - 迭代 Pandas 数据框的最快方法?

python - 修改 Flask-ReSTLess 的 JSON 响应

c++ - 猜谜游戏的随机生成器

.net - 使用变量、用户定义函数、自定义运算符的最佳免费 C# 数学解析器