Nano ID
Nano ID is a tiny, secure, URL-friendly, unique string ID generator for Python. It provides compact IDs that are safer and shorter than UUIDs by using a larger alphabet and cryptographically strong random APIs. The current stable version is 2.0.0, and it is actively maintained.
Warnings
- breaking Version 2.0.0 changed the default alphabet, replacing '~' with '-'. The default ID length was also reduced from 22 to 21 characters.
- gotcha The `non_secure_generate` function uses `random.random` internally and is not cryptographically strong. It is explicitly not recommended for security-sensitive applications like generating tokens or secrets.
- gotcha Reducing the ID length (e.g., `generate(size=10)`) increases the probability of collisions.
- gotcha When using custom alphabets, be cautious with characters like `-,.()` at the end of a link in URLs, as they might be misinterpreted as punctuation by some systems.
- gotcha NanoIDs are non-sequential. Using them as clustered primary keys in a database can lead to significant performance overhead during inserts, as the database may need to reorder records physically on disk to maintain the clustered index order.
Install
-
pip install nanoid
Imports
- generate
from nanoid import generate
- non_secure_generate
from nanoid import non_secure_generate
Quickstart
from nanoid import generate, non_secure_generate
# Generate a default 21-character, URL-friendly ID
id_default = generate()
print(f"Default ID: {id_default}")
# Generate an ID with a specified length
id_short = generate(size=10)
print(f"Short ID (10 chars): {id_short}")
# Generate an ID with a custom alphabet and length
id_custom = generate('1234567890abcdef', 16)
print(f"Custom Alphabet ID: {id_custom}")
# Generate a non-secure ID (faster, but not for sensitive use)
id_non_secure = non_secure_generate()
print(f"Non-Secure ID: {id_non_secure}")