Eliminate ID Generation Boilerplate Using the Python Secrets Module

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:

import random
import string


def generate_random_string(length):
    chars = string.ascii_letters + string.digits
    return "".join(random.choice(chars) for i in range(length))
    
# Generates string like
# tPII8dPGeAP46aA9

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:

import secrets

print(secrets.token_hex(16))
# 9a8e26d9c5e3fe5676d95752439882f6

Note: This string is 32 characters since 16 bytes of hex are generated with 2 digits each.

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!