V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
lichun
V2EX  ›  Python

Python 怎么写 retry 才够 pythonic?

  •  
  •   lichun · 2015-04-21 11:41:34 +08:00 · 5055 次点击
    这是一个创建于 3304 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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
    
    3 条回复    2016-07-04 03:30:48 +08:00
    dalang
        1
    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
        2
    dalang  
       2015-04-21 13:32:41 +08:00
    额,没对齐果真没法看。不确定回复支部支持 markdown,放个 gist 的链接

    https://gist.github.com/dalang/31d4bd34ff5c2f0b031a
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5497 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 07:56 · PVG 15:56 · LAX 00:56 · JFK 03:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.