Eliminate ID Generation Boilerplate Using the Python Secrets Module

submited by
Style Pass
2023-01-31 06:00:12

Secrets is a Python module that snuck into my Python installations, completely without my knowledge. Added in 2016, I had already been developing using Python for a few years and had developed my own methods for random ID generation. Oftentimes I would write some code that looked like this:

This is a perfectly fine way to generate a random ID that you want to use for sufficient uniqueness guarantees on things like uploaded files, or non-incremental IDs. But there is actually a better way to do this that you might not know about by using the "secrets" module. The code above can simply be replaced with:

While this is a relatively small optimization in the grand scheme of things, I always advocate for using the simplest and most secure methods for ID generation. So go use the secrets module today!

Leave a Comment