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
Post a Comment