Python Library of the Day: retrying

Python logoI’ve learned through extensive experience that Bash is the wrong choice for anything longer than a few lines. I needed to write a command line app, so I put one together in Python — Python 3 of course, as Python 2 is going away by 2020. In the process I discovered a new to me Python library called retrying.

If you want to learn Python, check out the Python for Data Science course on Cognitive Class.

retrying

I needed my Python code to repeat a bunch of operations until they succeeded. It’s easy to write a naive loop for that, but the logic gets convoluted and makes the actual operation ugly to look at. By the time you do something three times over, you should automate.

You can of course write an abstraction yourself, but for this sort of common problem it is best to use an existing library.

XKCD comic on automation

The benefit to using an existing library is not just that someone else maintains it, but also that you benefit from the collective wisdom and experience of everyone else using the library. Computing is full of strange edge cases and unexpected security holes. These are harder to avoid when rolling your own abstraction.

For my purpose, I found a Python library called retrying. It provides a simple decorator called @retry that you can apply to any function or method. The decorator also takes additional parameters so you can configure all the timeouts, intervals, exponential decay, and smart exception handling that you want.

Kudos to everyone working on the library. It’s a great little tool.

Published by

Leons Petrazickis

I’m a full-stack developer at IBM Digital Business Group. I do Ruby, Node, Python, Hadoop, Spark, as well as web scale devops with Docker and Terraform.

My opinions are my own.

Leave a Reply

Your email address will not be published. Required fields are marked *