Python Basics: Creating and Reading Identifiers with uuid
A record or import job often needs an identifier. Python’s standard-library uuid module can generate random IDs, recreate name-based IDs, and read existing UUID text.
Before you start
These independent examples were tested on Linux with Bash, Python 3.12.14 and Python 3.13.5. No packages or environment variables are required. The commands below use python3; use python3.13 instead to run them with that interpreter.
In one Bash session, create a fresh working directory:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save each source block below in this directory using the stated filename. Avoid uuid.py, which would shadow the standard-library module. The programs only print results; the files you save are the only files to clean up.
Generate a random identifier
Save as demo_uuid_1.py:
import uuid
job_id = uuid.uuid4()
print("Job ID:", job_id)
print("Version:", job_id.version)
print("Text length:", len(str(job_id)))
print("Hex length:", len(job_id.hex))Run it:
python3 demo_uuid_1.pyExample output; your Job ID will vary:
Job ID: 86a93966-20b9-4e93-8429-22cfed7fdec1
Version: 4
Text length: 36
Hex length: 32uuid4() generates a random UUID. str() includes hyphens, while .hex omits them. Generate an ID once and keep it with the record; rerunning the call does not recover an earlier ID. Random generation is not a mathematical guarantee against duplicates, so retain a database uniqueness constraint when required.
Recreate an ID from a name
Save as demo_uuid_2.py:
import uuid
page_url = "https://example.com/articles/python"
page_id = uuid.uuid5(uuid.NAMESPACE_URL, page_url)
same_id = uuid.uuid5(uuid.NAMESPACE_URL, page_url)
slash_id = uuid.uuid5(uuid.NAMESPACE_URL, page_url + "/")
print("Page ID:", page_id)
print("Version:", page_id.version)
print("Same input:", page_id == same_id)
print("Added slash:", page_id == slash_id)Run it:
python3 demo_uuid_2.pyOutput:
Page ID: a56f530a-1661-5540-9b54-c61a01a11508
Version: 5
Same input: True
Added slash: Falseuuid5() derives an ID from both a namespace UUID and a name. Identical inputs reproduce the result. It does not fetch or normalize the URL: a trailing slash changes this example’s ID. Decide on normalization rules before generating persistent IDs.
Parse text and handle invalid input
Save as demo_uuid_3.py:
import uuid
samples = [
"{67E55044-10B1-426F-9247-BB680E5FE0C8}",
"67e5504410b1426f9247bb680e5fe0c8",
"not-a-uuid",
]
for text in samples:
try:
identifier = uuid.UUID(text)
except ValueError:
print("Invalid:", text)
else:
print("Normalized:", identifier)Run it:
python3 demo_uuid_3.pyOutput:
Normalized: 67e55044-10b1-426f-9247-bb680e5fe0c8
Normalized: 67e55044-10b1-426f-9247-bb680e5fe0c8
Invalid: not-a-uuidBoth valid strings represent the same UUID. The malformed string intentionally exercises the error handler. Parsing checks the representation; it does not establish that a record exists or that someone may access it.
Use UUIDs as identifiers, not authentication secrets. A name-based UUID is reproducible, not encryption. For password-reset tokens or similar secrets, use a purpose-built security design and Python’s secrets module.
Clean up
After running the examples, remove their files and the empty working directory in the same Bash session:
rm -- demo_uuid_1.py demo_uuid_2.py demo_uuid_3.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirReferences
Acknowledgements
This post was created with assistance from AI.