我正在研究一个decorator,它将按如下方式最多重试运行N次函数:
def retry(exceptions, truncate=5, delay=0.25):
"""Retry the decorated function using an exponential backoff strategy.
If the function does not complete successfully a TimeoutException is
raised."""
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
tries = 0
while tries < truncate:
try:
return func(*args, **kwargs)
except exceptions, e:
print "%s, Retrying in %d seconds..." % (str(e), delay)
time.sleep(delay)
>> delay += delay
tries += 1
else:
raise TimeoutException()
return wrapped
return wrapper
对我来说,代码看起来很合理,但在这行中突出显示了pyflakes的抱怨,报告:
W804局部变量“delay”(在第x行的封闭范围中定义)
分配前引用
这对我来说不太有意义。
delay
已经分配了一个值,我大概应该可以作为I please引用它。有人能解释一下错误是什么吗?如果合理的话,我该怎么解决? 最佳答案
如果您尝试运行此代码,它实际上会崩溃。问题在于,在嵌套作用域(如wrapped
(和wrapper
)中,可以读取外部变量,但不能将其赋值。
这就是3.x中the nonlocal
keyword的用途(这将使delay
的所有“实例”从单个调用增加到wrapped
)。要在2.x中复制它,您需要执行类似retry
的操作,并将其作为delay_lst = [delay]
访问。
如果您希望修改是delay_lst[0]
本地的,只需创建一个新变量并用wrapped
的值初始化它。
关于python - pyflakes w804代表什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11728960/