推荐学习书目
› 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 · Apr 21, 2015 · 5763 views
    This topic created in 4175 days ago, the information mentioned may be changed or developed.

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

    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 replies  •  2016-07-04 03:30:48 +08:00
    dalang
        1
    dalang  
       Apr 21, 2015
    其实我觉得没什么问题。只是直接捕获 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  
       Apr 21, 2015
    额,没对齐果真没法看。不确定回复支部支持 markdown,放个 gist 的链接

    https://gist.github.com/dalang/31d4bd34ff5c2f0b031a
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2388 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:58 · PVG 12:58 · LAX 21:58 · JFK 00:58
    ♥ Do have faith in what you're doing.