Wednesday, 13 November 2013

Retry python decorator

A common case is to defence code against connection timeouts, which is commonly achieved by applying a retry strategy to the vulnerable code. With python you would typically run the vulnerable code in a try block, catch the exception and if the number of retries hasn't been reached yet you would retry the code, else you would re-raise the exception.

I found myself repeating this pattern a lot and found lots of places where I had missed adding this and in large part was that the code to do this is a few lines. So I wanted to create a simple decorator so going forward I could simply decorate the method and be done with it - perfect.

I searched around and found on the Python Wiki there was an example of a retry decorator that would retry based on the return value being False. I simply edited this code to instead retry based on an exception being raised.

Simply stick @retry(10) above a method to make it retry itself 10 times if an exception is raised.

I have included the @functools.wrap decorator so that my docstrings are retained which I use to auto generate sphinx documentation.

Here is an example usage when dealing with boto and SQS...beautiful if I do say so myself.

No comments:

Post a Comment