Course contentsShow
← Python
Lesson 730 of 1,06011. Standard Library EssentialsFree lesson

Creating Unique Identifiers with uuid

Generate uuid4 identifiers and convert them to standard strings for records and resources, without treating identifiers as authentication secrets.

In this lesson, you will learn how to generate cryptographically robust, unique identifiers for your application’s records and resources using the uuid module.

Understanding UUIDs

A Universally Unique Identifier (UUID) is a 128-bit number used to label information in computer systems. Because they are designed to be statistically unique across space and time, you can generate them independently without needing a central authority or a database sequence to ensure no two IDs clash.

In Python, the uuid module provides different versions, but uuid4 is the standard choice for most application needs. It generates a random UUID, making it perfect for primary keys in distributed databases, session tokens, or unique filenames.

Generating a Random Identifier

To create a UUID, import the uuid module and call uuid4(). Because a UUID object is a complex data structure, you will typically convert it to a standard hexadecimal string to store it in a JSON file or a database record.

import uuid

# Generate a random UUID object
unique_id = uuid.uuid4()

# Convert to a standard 36-character string (8-4-4-4-12 format)
id_string = str(unique_id)

print(f"Generated Record ID: {id_string}")

A Note on Security

It is vital to distinguish between a unique identifier and an authentication secret. While uuid4 is random and difficult to guess, it is not a secure cryptographic key. Never rely on a UUID alone to prove a user's identity or to secure sensitive resources. Use UUIDs exclusively for indexing, tagging, and organizing your data records.

By treating these IDs as simple labels rather than security credentials, you ensure your system remains scalable and easy to audit without introducing hidden vulnerabilities. Using uuid4 consistently across your application layers—from file naming to database entries—creates a clean, collision-resistant infrastructure for your resources.

Key Takeaway: Use uuid.uuid4() to generate collision-resistant identifiers for data records, and always convert them to strings for consistent storage and readability.