Skip to main content

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

Featureuuid1()uuid4()
Based onTimestamp + MAC addressRandom bytes
UniquenessGuaranteed (uses hardware ID)Statistically unique (2^122 possible)
PrivacyLeaks MAC address and creation timeNo information leakage
SortableRoughly time-orderedCompletely random
Best forInternal systems, event loggingPublic 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 filenamesf\"{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

Try UUID v4 Generator Free

Generate unique UUID v4 identifiers.

Use UUID v4 Generator →