2013-08-07 166 views
2

我是新来的蟒蛇。我试图创建一个重试装饰器,当应用于一个函数时,它将继续重试,直到满足一些条件(为了简单起见,重试10次)。我可以将异常作为参数传递给python中的函数吗?

def retry(): 
    def wrapper(func): 
     for i in range(0,10): 
      try: 
       func() 
       break 
      except: 
       continue 
    return wrapper 

现在,将重试任何异常。我如何改变它,使其重试特定的例外情况。 e.g,我想用它喜欢:

@retry(ValueError, AbcError) 
def myfunc(): 
    //do something 

我想myfunc将仅重试它抛出ValueErrorAbcError

+0

现在增加了一个'break'。谢谢!。编辑:我认为这是重试的逻辑错误。我只需要'for'循环我认为 –

回答

8

您可以提供异常的tupleexcept ..块捕捉:

from functools import wraps 

def retry(*exceptions, **params): 
    if not exceptions: 
     exceptions = (Exception,) 
    tries = params.get('tries', 10) 

    def decorator(func): 
     @wraps(func) 
     def wrapper(*args, **kw): 
      for i in range(tries): 
       try: 
        return func(*args, **kw) 
       except exceptions: 
        pass 
     return wrapper 
    return decorator 

包罗万象的*exceptions参数将总是导致一个元组。我添加了一个tries关键字一样,所以你可以配置重过数量:

@retry(ValueError, TypeError, tries=20) 
def foo(): 
    pass 

演示:

>>> @retry(NameError, tries=3) 
... def foo(): 
...  print 'Futzing the foo!' 
...  bar 
... 
>>> foo() 
Futzing the foo! 
Futzing the foo! 
Futzing the foo! 
+0

其实你可以捕捉到一个“可变异常或你可以捕捉的东西的元组”,但是如果我想得太久,这往往会让我头痛。 – Duncan

+0

@Duncan:是的,咖啡因短缺正在影响我的文法中心。 –

+0

@glglgl:它需要的不仅仅是“返回包装”,这使它成为一个合适的装饰工厂。 –

0

您可以检查错误类:

except Exception as e: 
    for et in error_types: #(or args) 
     if isinstance(e, et): 
      continue 
    raise e #re-raise 
+0

除了一个可以迭代的对象(例如元组,列表)以外,所以不需要稍后迭代。 –

2
from functools import wraps 

class retry(object): 
    def __init__(self, *exceptions): 
     self.exceptions = exceptions 

    def __call__(self, f): 
     @wraps(f) # required to save the original context of the wrapped function 
     def wrapped(*args, **kwargs): 
      for i in range(0,10): 
       try: 
        f(*args, **kwargs) 
       except self.exceptions: 
        continue 
     return wrapped 

用法:

@retry(ValueError, Exception) 
def f(): 
    print('In f') 
    raise ValueError 


>>> f() 
In f 
In f 
In f 
In f 
In f 
In f 
In f 
In f 
In f 
In f 
相关问题