Python

Generate UUID in Python

Complete guide to the built-in uuid module — uuid4, uuid1, uuid3, uuid5, Django, FastAPI, and database best practices.

Need a UUID right now? Generate one in your browser — no code required.

Open UUID v4 Generator →

The Quick Answer

Python ships with a uuid module in the standard library. No pip install needed.

Python — generate UUID v4 (one line)
import uuid

unique_id = str(uuid.uuid4())
print(unique_id)
# → "f47ac10b-58cc-4372-a567-0e02b2c3d479"

That's it. uuid.uuid4() returns a UUID object; wrapping it in str() gives the standard hyphenated string representation.

All UUID Versions in Python

The uuid module supports all common UUID versions.

UUID v4 — Random (recommended for most use cases)

uuid4 — cryptographically random UUID
import uuid

# Standard hyphenated format
uid = str(uuid.uuid4())            # "f47ac10b-58cc-4372-a567-0e02b2c3d479"

# Without hyphens (32 hex chars)
uid_hex = uuid.uuid4().hex         # "f47ac10b58cc4372a5670e02b2c3d479"

# Raw bytes (16 bytes)
uid_bytes = uuid.uuid4().bytes     # b'\xf4z\xc1\x0bX\xccC...'

# As integer
uid_int = uuid.uuid4().int         # 323910690...

# Back from string
existing = uuid.UUID("f47ac10b-58cc-4372-a567-0e02b2c3d479")

UUID v1 — Timestamp + MAC address

uuid1 — timestamp-based UUID
import uuid

uid = str(uuid.uuid1())
# → "6ba7b810-9dad-11d1-80b4-00c04fd430c8"

# Note: encodes the current timestamp and your machine's MAC address.
# Avoid when privacy matters — use uuid4() instead.

UUID v3 and v5 — Name-based (deterministic)

uuid3 / uuid5 — same name → same UUID every time
import uuid

# UUID v3 (MD5-based) — not recommended for new code
uid_v3 = str(uuid.uuid3(uuid.NAMESPACE_DNS, "example.com"))
# → "5df41881-3aed-3515-88a7-2f4a814cf09e"

# UUID v5 (SHA-1-based) — preferred over v3
uid_v5 = str(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))
# → "cfbff0d1-9375-5685-968c-48ce8b15ae17"

# Built-in namespaces: NAMESPACE_DNS, NAMESPACE_URL, NAMESPACE_OID, NAMESPACE_X500
# Same inputs always produce the same UUID — useful for idempotent IDs.

UUID in Django

Django has native UUID support. Use UUIDField to store UUIDs as a proper 128-bit column in supported databases (PostgreSQL, MySQL 8+) or as a char(32) elsewhere.

Django — UUIDField as primary key
import uuid
from django.db import models

class Product(models.Model):
    # UUID primary key — auto-generated, never sequential
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,   # pass the function, not the call
        editable=False,
    )
    name = models.CharField(max_length=200)

    class Meta:
        ordering = ["-created_at"]

# In templates / serializers, access it as a string:
# str(product.id) → "f47ac10b-58cc-4372-a567-0e02b2c3d479"

Pass uuid.uuid4 (no parentheses) as default so Django calls the function per row, not once at import time.

UUID in FastAPI and Pydantic

FastAPI — UUID path parameter and Pydantic model
from uuid import UUID, uuid4
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Item(BaseModel):
    id: UUID = Field(default_factory=uuid4)
    name: str

@app.get("/items/{item_id}")
async def get_item(item_id: UUID):
    # FastAPI validates the path param is a valid UUID automatically
    return {"id": str(item_id)}

@app.post("/items")
async def create_item(item: Item):
    return item  # id is auto-generated if not supplied

UUID Version Comparison

Which Python uuid function should you use?

Function Algorithm Sortable Privacy-safe Use case
uuid.uuid4() OS CSPRNG No Yes Default choice — session tokens, IDs, keys
uuid.uuid1() Timestamp + MAC Roughly No Legacy systems, rarely needed
uuid.uuid3(ns, name) MD5 No Yes Avoid — MD5 is weak; use uuid5 instead
uuid.uuid5(ns, name) SHA-1 No Yes Deterministic IDs from known strings

Frequently Asked Questions

Does Python's uuid.uuid4() use a cryptographically secure random source?

Yes. uuid.uuid4() uses os.urandom() internally, which pulls from the operating system's CSPRNG (/dev/urandom on Linux/macOS, BCryptGenRandom on Windows). This is the same entropy source used for TLS. It is safe for security-sensitive use cases such as session tokens and primary keys.

Do I need to install anything to use uuid in Python?

No. The uuid module is part of Python's standard library since Python 2.5. Just import uuid at the top of your file — no pip install required.

How do I store a UUID in a Python string vs UUID object?

uuid.uuid4() returns a UUID object. Call str() on it to get the hyphenated string form (e.g. '550e8400-e29b-41d4-a716-446655440000'). Use .hex to get the 32-character form without hyphens. Use .bytes to get the raw 16-byte binary representation.

What is the difference between uuid4() and uuid1() in Python?

uuid.uuid4() generates a random UUID using the OS CSPRNG — it contains no identifying information and is the recommended choice for most use cases. uuid.uuid1() generates a UUID based on the current timestamp and the host machine's MAC address — it can theoretically leak network information and is rarely needed today. Use uuid4() unless you specifically need timestamp traceability.

Is uuid4 safe to use as a database primary key in Python?

It is safe in terms of uniqueness and security. However, random v4 UUIDs cause B-tree index fragmentation in relational databases because rows are inserted in random order rather than sequentially. For high-write PostgreSQL or MySQL tables, consider a time-ordered alternative like UUID v7 (not yet in Python stdlib — use the uuid6 package) or ulid-py.

Related Tools & Guides