UUID Module: Generating Universally Unique Identifiers
TL;DR
The uuid module generates 128-bit universally unique identifiers using multiple methods - random (uuid4), time-based (uuid1), or namespace-based (uuid3/uuid5) - perfect for unique IDs in databases and distributed systems.
Interesting!
UUIDs are so mathematically unlikely to collide that you could generate a billion UUIDs every second for 85 years and have less than a 50% chance of creating a duplicate.
UUID Generation Methods
Random UUIDs (Most Common)
python code snippet start
import uuid
# Generate a random UUID
user_id = uuid.uuid4()
print(user_id) # e.g., 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
# Convert to string for databases
user_id_str = str(user_id)
python code snippet end
Time-Based UUIDs
python code snippet start
# UUID based on host ID and timestamp
time_uuid = uuid.uuid1()
print(time_uuid) # Contains MAC address and timestamp
python code snippet end
Namespace-Based UUIDs
python code snippet start
# Deterministic UUID from namespace and name
dns_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
print(dns_uuid) # Always the same for 'python.org'
# Custom namespace
custom_namespace = uuid.uuid4()
app_uuid = uuid.uuid5(custom_namespace, 'user-123')
python code snippet end
Format Conversions
python code snippet start
my_uuid = uuid.uuid4()
# Different representations
print(my_uuid.hex) # 32 character hex string
print(my_uuid.bytes) # 16-byte binary
print(my_uuid.int) # 128-bit integer
print(my_uuid.urn) # URN format
python code snippet end
Best Practices
Use uuid4()
for general unique IDs:
python code snippet start
# Perfect for database primary keys
import uuid
def create_user(name):
return {
'id': str(uuid.uuid4()),
'name': name,
'created_at': datetime.now()
}
python code snippet end
Avoid uuid1()
in privacy-sensitive applications as it may expose MAC addresses. Use uuid with database primary keys
and secure token generation
. For time-based applications, combine with datetime handling
and JSON serialization
for APIs.
Reference: Python UUID Documentation