Generate UUID in Python: uuid Module Complete Guide
Generate UUIDs in Python using the uuid module. uuid1 vs uuid4, UUID objects, database storage, string conversion, and Django/SQLAlchemy integration.
How to Generate UUIDs in Python
Python's built-in uuid module provides functions for all UUID versions. For most applications, uuid.uuid4() generates a random UUID using the operating system's cryptographic random number generator — no external packages needed.
Basic UUID Generation
import uuid
# Generate a random UUID v4
id = uuid.uuid4()
print(id) # UUID object: 7c9e6679-7425-40de-944b-e07fc1f90ae7
print(str(id)) # String: \"7c9e6679-7425-40de-944b-e07fc1f90ae7\"
print(id.hex) # No dashes: \"7c9e667974254de944be07fc1f90ae7\"
print(id.bytes) # 16 bytes of raw binary
print(id.int) # 128-bit integer representation
# Generate from a string
id = uuid.UUID(\"7c9e6679-7425-40de-944b-e07fc1f90ae7\")
print(id.version) # 4
UUID1 vs UUID4
| Feature | uuid1() | uuid4() |
|---|---|---|
| Based on | Timestamp + MAC address | Random bytes |
| Uniqueness | Guaranteed (uses hardware ID) | Statistically unique (2^122 possible) |
| Privacy | Leaks MAC address and creation time | No information leakage |
| Sortable | Roughly time-ordered | Completely random |
| Best for | Internal systems, event logging | Public IDs, API keys, databases |
Use uuid4() unless you specifically need time-based ordering and your UUIDs are never exposed to end users.
Database Integration
# Django model with UUID primary key
import uuid
from django.db import models
class Order(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
customer_name = models.CharField(max_length=200)
# SQLAlchemy with UUID column
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)
UUID as Dictionary Keys and Set Members
import uuid
# UUID objects are hashable — usable as dict keys
cache = {}
key = uuid.uuid4()
cache[key] = {\"data\": \"value\"}
# Comparison works correctly
id1 = uuid.UUID(\"7c9e6679-7425-40de-944b-e07fc1f90ae7\")
id2 = uuid.UUID(\"7c9e6679-7425-40de-944b-e07fc1f90ae7\")
print(id1 == id2) # True
print(id1 is id2) # False (different objects)
Common Patterns
- Unique filenames —
f\"{uuid.uuid4()}.png\"prevents upload collisions - Correlation IDs — pass a UUID through microservice call chains for distributed tracing
- Idempotency tokens — attach a UUID to payment requests to prevent double charges
- Test data factories — generate unique identifiers for test fixtures without hardcoding