How to Generate a UUID in Python
- Python stdlib: import uuid — no installation needed
- uuid.uuid4() for random UUID v4 — the default choice
- Convert to string: str(uuid.uuid4()) — outputs standard hyphenated format
- No-dashes: str(uuid.uuid4()).replace("-", "") or uuid.uuid4().hex
Table of Contents
Python generates UUIDs with its built-in uuid module — no pip install required. uuid.uuid4() returns a random v4 UUID in one line. This guide covers every Python UUID method with copy-paste examples, string formatting options, and when to use each version.
uuid.uuid4() — The Standard Method for Random UUIDs
import uuid # Generate a single UUID v4 new_id = uuid.uuid4() print(new_id) # Output: 550e8400-e29b-41d4-a716-446655440000 # As a string (most common usage) id_str = str(uuid.uuid4()) print(id_str) # Output: '550e8400-e29b-41d4-a716-446655440000' # As a string without dashes id_no_dashes = uuid.uuid4().hex print(id_no_dashes) # Output: '550e8400e29b41d4a716446655440000' # Uppercase id_upper = str(uuid.uuid4()).upper() print(id_upper) # Output: '550E8400-E29B-41D4-A716-446655440000'
uuid.uuid4() uses os.urandom() internally — cryptographically secure random bytes from your OS. It is the right choice for database IDs, session tokens, API keys, and any other use case where you need a unique identifier.
All Python UUID Methods — uuid1, uuid3, uuid4, uuid5
| Method | Type | When to Use |
|---|---|---|
uuid.uuid1() | Time + MAC address | When you need sortable UUIDs or want embedded timestamp. Leaks MAC address — avoid for public-facing IDs. |
uuid.uuid3(name, namespace) | MD5 hash of input | Deterministic UUID from a string. Same input always produces the same UUID. Good for idempotent operations. |
uuid.uuid4() | Random (crypto) | Default choice. Random, no embedded info, crypto-secure. |
uuid.uuid5(name, namespace) | SHA-1 hash of input | Like uuid3 but uses SHA-1. Preferred over uuid3 for new code. |
import uuid # uuid3 and uuid5 — deterministic from string input namespace = uuid.NAMESPACE_DNS name_based_3 = uuid.uuid3(namespace, 'example.com') print(name_based_3) # Always: '5df41881-3aed-3515-88a7-2f4a814cf09e' name_based_5 = uuid.uuid5(namespace, 'example.com') print(name_based_5) # Always: '2ed6657d-e927-568b-95e3-af9b2-6b2d39' # Available namespaces print(uuid.NAMESPACE_DNS) print(uuid.NAMESPACE_URL) print(uuid.NAMESPACE_OID) print(uuid.NAMESPACE_X500)Sell Custom Apparel — We Handle Printing & Free Shipping
Common UUID Operations in Python
import uuid
# Generate multiple UUIDs
uuids = [str(uuid.uuid4()) for _ in range(10)]
print(uuids)
# Parse/validate a UUID string
try:
parsed = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
print(parsed.version) # Output: 4
print(parsed.hex) # '550e8400e29b41d4a716446655440000'
print(parsed.int) # integer representation
except ValueError:
print('Invalid UUID')
# Check UUID version
def get_uuid_version(uuid_str):
try:
return uuid.UUID(uuid_str).version
except ValueError:
return None
# UUID as bytes (16 bytes binary)
u = uuid.uuid4()
print(u.bytes) # 16-byte binary
print(u.bytes_le) # little-endian variant
UUID in Django and SQLAlchemy
Django — 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
)
# Note: default=uuid.uuid4 (not uuid.uuid4())
# Pass the function, not the result
SQLAlchemy
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import UUID
import uuid
class Order(Base):
__tablename__ = 'orders'
id = Column(
UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid4
)
When you just need a quick UUID to test with rather than running your full application, the WildandFree UUID Generator gives you one instantly in your browser — useful for seeding test fixtures or checking query behavior.
Performance Notes for High-Volume UUID Generation
Python's uuid.uuid4() is fast but not the fastest option if you are generating millions of UUIDs in a tight loop:
import time
import uuid
# Standard uuid4
start = time.time()
for _ in range(1_000_000):
str(uuid.uuid4())
print(f'uuid4: {time.time() - start:.2f}s')
# Typical: ~1.5-2s on modern hardware
# Faster: generate bytes directly
import os
def fast_uuid():
b = bytearray(os.urandom(16))
b[6] = (b[6] & 0x0f) | 0x40 # version 4
b[8] = (b[8] & 0x3f) | 0x80 # variant
return '%08x-%04x-%04x-%04x-%012x' % (
int.from_bytes(b[0:4],'big'),
int.from_bytes(b[4:6],'big'),
int.from_bytes(b[6:8],'big'),
int.from_bytes(b[8:10],'big'),
int.from_bytes(b[10:16],'big')
)
For most applications, the standard uuid.uuid4() is fast enough. Micro-optimization is only worthwhile if UUID generation appears in profiling as a bottleneck.
Need a UUID Right Now? Skip the Code
Sometimes you just need one UUID to paste into a test or a database record. Generate one (or ten) instantly in your browser — no Python, no library, no signup.
Open Free UUID GeneratorFrequently Asked Questions
What is the difference between uuid.uuid4() and uuid.uuid4().hex?
uuid.uuid4() returns a UUID object. str(uuid.uuid4()) gives "550e8400-e29b-41d4-a716-446655440000" with hyphens. uuid.uuid4().hex gives "550e8400e29b41d4a716446655440000" — the same value without hyphens, as a plain hex string.
Is Python uuid.uuid4() cryptographically secure?
Yes. Python's uuid4() reads from os.urandom() which uses the operating system's cryptographically secure random number generator (/dev/urandom on Linux/Mac, CryptGenRandom on Windows). It is safe to use for session tokens, API keys, and any security-sensitive identifier.
How do I generate a UUID v7 in Python?
Python's standard library does not include uuid7 yet. Use the uuid6 package: pip install uuid6, then import uuid6; uid = uuid6.uuid7(). UUID v7 is time-ordered, which improves database index performance. See our UUID version guide for when v7 is worth the extra dependency.
How do I validate that a string is a valid UUID in Python?
Use try/except with uuid.UUID(). If the string is not a valid UUID, it raises ValueError. Example: try: uuid.UUID(my_string); except ValueError: handle_invalid(). This validates format but not version — check uuid.UUID(s).version if version matters.

