V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · 5512 views
    This topic created in 4036 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   ·   Solana   ·   2855 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 02:00 · PVG 10:00 · LAX 19:00 · JFK 22:00
    ♥ Do have faith in what you're doing.