Trap exception, try again decorator in Python

Viewed 580

I have little experience with decorators in Python, but I'd like to write a function decorator that runs the function, catches a specific exception, and if the exception is caught then re-tries the function a certain number of times. That is, I'd like to do this:

@retry_if_exception(BadStatusLine, max_retries=2)
def thing_that_sometimes_fails(self, foo):
   foo.do_something_that_sometimes_raises_BadStatusLine()

I assume this kind of thing is easy with decorators, but I'm not clear about how exactly to go about it.

4 Answers
Related