Python 怎么写 retry 才够 pythonic?

2015-04-21 11:41:34 +08:00
 lichun

自己用装饰器写了一个,有什么需要改进的地方吗?

def retry(attempt):
    def decorator(func):
        def wrapper(*args, **kw):
            att = 0
            while att < attempt:
                try:
                    return func(*args, **kw)
                except Exception as e:
                    att += 1
        return wrapper
    return decorator


@rety(attempt=3)
def get_response(url):
    import requests
    r = requests.get('http://xxx')
    return r.content
5064 次点击
所在节点    Python
3 条回复
dalang
2015-04-21 13:24:14 +08:00
其实我觉得没什么问题。只是直接捕获 Exception 对后期排障有隐患,而且我更倾向于能明确告知调用者 retry 失败的原因。

def retry(attempt, raise_on_fail=False):
def decorator(func):
def wrapper(*args, **kw):
att = 0
last_except = None
while att < attempt:
try:
return func(*args, **kw)
except Exception as e:
att += 1
last_except = e
else:
if raise_on_fail:
raise Exception('Hit retry threshold, failed for {0}' % str(last_except))
return None
return wrapper
return decorator
dalang
2015-04-21 13:32:41 +08:00
额,没对齐果真没法看。不确定回复支部支持 markdown,放个 gist 的链接

https://gist.github.com/dalang/31d4bd34ff5c2f0b031a
fzinfz
2016-07-04 03:30:48 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/185178

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX