Generate UUIDs in Python
How to generate UUIDs in Python using the built-in uuid module: uuid4(), uuid1(), uuid5(), uuid3(), and the new uuid7() in Python 3.14 with examples.
Detailed Explanation
Python's standard library includes a comprehensive uuid module that supports all major UUID versions without any third-party dependencies.
UUID v4 (random):
import uuid
id = uuid.uuid4()
print(id) # e.g., 7c2d9e8a-3f4b-4a1c-9d5e-6f7a8b9c0d1e
print(id.hex) # 7c2d9e8a3f4b4a1c9d5e6f7a8b9c0d1e (no hyphens)
print(id.bytes) # b'|-.\x8a?K....' (16 bytes)
print(id.int) # Integer representation
print(id.version) # 4
UUID v1 (timestamp + MAC):
id = uuid.uuid1()
print(id.time) # 100-ns intervals since 1582-10-15
print(id.node) # MAC address as integer
UUID v3 and v5 (name-based):
# v5 (SHA-1, recommended)
id = uuid.uuid5(uuid.NAMESPACE_DNS, "example.com")
# cfbff0d1-9375-5685-968c-48ce8b15ae17
# v3 (MD5, legacy)
id = uuid.uuid3(uuid.NAMESPACE_DNS, "example.com")
# 9073926b-929f-31c2-abc9-fad77ae3e8eb
# Available namespaces:
# uuid.NAMESPACE_DNS, uuid.NAMESPACE_URL,
# uuid.NAMESPACE_OID, uuid.NAMESPACE_X500
UUID v7 (Python 3.14+):
Starting with Python 3.14 (expected release: October 2025), the uuid module includes native UUID v7 support:
id = uuid.uuid7() # Time-ordered, database-friendly
For earlier Python versions, use the uuid7 or uuid-utils package from PyPI:
# pip install uuid-utils
from uuid_utils import uuid7
id = uuid7()
UUID operations:
# Parse from string
id = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
# Compare UUIDs
uuid.uuid4() == uuid.uuid4() # False (virtually always)
# Sort UUIDs (works correctly for v7)
ids = [uuid.uuid4() for _ in range(5)]
ids.sort() # Sorts by internal integer value
# Convert to/from bytes (for database storage)
raw = id.bytes # 16 bytes
restored = uuid.UUID(bytes=raw)
# Nil UUID
nil = uuid.UUID(int=0)
Django integration:
from django.db import models
class MyModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# Note: pass uuid.uuid4 (the function), not uuid.uuid4() (a value)
SQLAlchemy integration:
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import UUID
import uuid
class User(Base):
__tablename__ = 'users'
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
Performance: Python's uuid.uuid4() generates approximately 500K UUIDs per second on modern hardware. If you need higher throughput, the uuid-utils package (written in Rust) achieves 2-5x faster generation.
Use Case
Python UUID generation is ubiquitous in Django and FastAPI web applications for creating primary keys, as well as in data engineering pipelines for assigning unique identifiers to ETL batch records.