I've discovered a gap in existing retry decorators available on PyPI. Most libraries limit retries to functions or lambdas, but I needed something that could retry an arbitrary block of code. So, I created a library called **loopretry**. It combines an iterator with a context manager to allow any code block to be retried in the event of an exception. Here's a quick example: you can wrap any block you want to retry, like this:
from loopretry import retries
import time
for retry in retries(10):
with retry():
print(time.time())
assert int(time.time()) % 10 == 0, "Not a round number!"
Is this approach novel, or are there similar implementations out there? Any feedback on the library code would also be appreciated. You can check it out on GitHub or install it via `pip install loopretry`.
4 Answers
Have you looked into Stamina? It provides a retry context that works great for async code. You can define retries for HTTP requests too, which might be relevant for your use case.
Actually, the Tenacity library can accomplish this too! You can try checking their documentation for how to retry code blocks directly.
I wish I had found it before I wrote my own library! Those library names are so hard to guess sometimes.
It would be super handy to have a backoff function in your library for requests. I think that could make it even easier to use!
That's a great idea! I actually included a basic sleep function, but adding a backoff coefficient could definitely enhance it. Thanks for the suggestion!
I once had a wild experience with nested retry loops causing my code to block for ages. Different developers had added their own layers without realizing it! In my case, it was an issue that wouldn’t resolve with retries at all.
That's a funny story! My use case is specific to waiting for metrics, and I think having retries for small blocks seems like the simplest solution.

I searched thoroughly before creating my library but must have missed Stamina. I'll look into it!