decorator - Can I pass an exception as an argument to a function in python? -


i new python. trying create retry decorator that, when applied function, keep retrying until criteria met (for simplicity, retry 10 times).

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

now retry on exception. how can change such retries on specific exceptions. e.g, want use like:

@retry(valueerror, abcerror) def myfunc():     //do 

i want myfunc retried of throws valueerror or abcerror.

you can supply tuple of exceptions except .. block catch:

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):             in range(tries):                 try:                     return func(*args, **kw)                 except exceptions:                     pass         return wrapper     return decorator 

the catch-all *exceptions parameter result in tuple. i've added tries keyword well, can configure number of retries too:

@retry(valueerror, typeerror, tries=20) def foo():     pass 

demo:

>>> @retry(nameerror, tries=3) ... def foo(): ...     print 'futzing foo!' ...     bar ...  >>> foo() futzing foo! futzing foo! futzing foo! 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -