Working with UUIDs in Python
Python's standard library includes a comprehensive uuid module that covers all standard UUID versions. Here is everything you need to know.
Generating UUIDs
import uuid
# UUID v4 (random) — most common
v4 = uuid.uuid4()
print(v4) # "3a2e6b1f-8d4c-4e5f-a6b7-123456789abc"
print(v4.hex) # "3a2e6b1f8d4c4e5fa6b7123456789abc" (no hyphens)
# UUID v1 (time + MAC address)
v1 = uuid.uuid1()
print(v1) # "c1c4f0e0-3a2b-11ee-be56-0242ac120002"
print(v1.time) # Unix timestamp of creation
# UUID v5 (SHA-1 hash of namespace + name)
NAMESPACE_DNS = uuid.UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
v5 = uuid.uuid5(NAMESPACE_DNS, 'example.com')
print(v5) # Always produces the same UUID for "example.com" Parsing and Validating
# Parse a UUID string
u = uuid.UUID('3a2e6b1f-8d4c-4e5f-a6b7-123456789abc')
print(u.version) # 4
print(u.variant) # RFC 4122
# Parse from raw hex
u = uuid.UUID('3a2e6b1f8d4c4e5fa6b7123456789abc')
print(str(u)) # "3a2e6b1f-8d4c-4e5f-a6b7-123456789abc"
# Check if a string is a valid UUID
def is_valid_uuid(s):
try:
uuid.UUID(s)
return True
except (ValueError, AttributeError):
return False Using UUIDs with Django
Replace Django's default auto-increment integer IDs with UUID fields:
import uuid
from django.db import models
class User(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
name = models.CharField(max_length=255)
email = models.EmailField(unique=True) SQLAlchemy with UUID Primary Keys
import uuid
from sqlalchemy import Column, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(
UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid4
)
email = Column(String(255), unique=True, nullable=False) Performance Considerations
Prefer uuid.uuid4() over uuid.uuid1() unless you specifically need time-based or MAC-address-embedded UUIDs. UUID v1 leaks information about your machine and the time of generation. For Python 3.12+, the uuid module is implemented in C for better performance.
When storing UUIDs in PostgreSQL via SQLAlchemy, use UUID(as_uuid=True) to store them as native PostgreSQL UUID type (16 bytes binary) rather than text, which is significantly more efficient for storage and indexing.