Use Python’s built-in uuid.uuid4() (import uuid; str(uuid.uuid4())) to generate a cryptographically random 128-bit Universally Unique Identifier (UUID / Microsoft GUID), or uuid.uuid7() in Python 3.14+ when you need time-ordered, database-index-friendly UUIDs.

Basic Example

import uuid

# 1. Recommended (general-purpose random UUID v4 — standard across APIs & databases):
uid = uuid.uuid4()
print(uid)          # Output: 3f2504e0-4f89-41d3-9a0c-0305e82c3301 (uuid.UUID object)
print(str(uid))     # Output: '3f2504e0-4f89-41d3-9a0c-0305e82c3301' (canonical 36-char string)
print(uid.hex)      # Output: '3f2504e04f8941d39a0c0305e82c3301' (32-char hex without hyphens)

# 2. Deterministic UUID v5 (same namespace + name ALWAYS produces the exact same UUID):
ns_uid = uuid.uuid5(uuid.NAMESPACE_DNS, "example.com")
print(ns_uid)       # Output: cfbff0d1-9375-5685-968c-48ce8b15ae17

# 3. Parse/validate an existing UUID or GUID string (accepts braces & uppercase):
parsed = uuid.UUID("{3F2504E0-4F89-41D3-9A0C-0305E82C3301}")
print(parsed == uid)  # Output: True

Key Details & Edge Cases

  • uuid.uuid4() returns a uuid.UUID object, NOT a str:
    • Always convert with str(uuid.uuid4()) before serializing to JSON (json.dumps raises TypeError: Object of type UUID is not JSON serializable), concatenating into strings, or passing to drivers that expect string keys.
  • UUID vs. Microsoft GUID (uuid.UUID handles both identically):
    • Microsoft’s GUID is simply an implementation of the RFC 4122 / RFC 9562 UUID standard. uuid.UUID() automatically parses Microsoft-style uppercase braced strings ("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"), and you can format back to uppercase GUID style via f"{{{str(uid).upper()}}}".
    • Note: If interoperating with legacy Windows COM/Registry binary layouts (bytes_le), use uid.bytes_le (little-endian first 3 fields) vs. uid.bytes (standard big-endian RFC network byte order).
  • Avoid uuid.uuid1() in public APIs or web apps (privacy leak):
    • uuid.uuid1() embeds your machine’s physical 48-bit MAC address and exact creation timestamp inside the UUID, exposing server hardware identifiers and creation times to external users. Prefer uuid.uuid4() (random) or uuid.uuid7() (time-ordered with random bits, Python 3.14+).
  • Database primary key performance (uuid4 vs. uuid7):
    • Completely random uuid.uuid4() values cause B-tree page splits and index fragmentation when inserted at high volume as clustered primary keys in PostgreSQL, MySQL, or SQLite. On Python 3.14+, use uuid.uuid7() (RFC 9562 Unix-epoch timestamp prefix + random suffix) for monotonically increasing primary keys.
  • Safe validation of untrusted user-supplied UUID strings:
    • Wrap uuid.UUID(raw_str) in a try...except (ValueError, AttributeError, TypeError): block—and note that uuid.UUID() accepts 32-char hex without hyphens by default, so check str(parsed) == raw_str.lower() if you require strict hyphenated canonical format.

Comparison of Python uuid Module Functions

Function RFC Version Generation Basis Deterministic? Best Used When
uuid.uuid4() (Recommended) UUID v4 Cryptographic OS randomness (os.urandom) No (unique random ID every call) General-purpose unique IDs, request correlation IDs, tokens, and filenames.
uuid.uuid7() (Python 3.14+) UUID v7 Unix millisecond timestamp + random bits No (monotonically sortable by time) High-throughput database primary keys requiring B-tree index locality.
uuid.uuid5(namespace, name) UUID v5 SHA-1 hash of namespace UUID + name string Yes (same inputs $\rightarrow$ identical UUID) Generating reproducible IDs from natural keys (URLs, emails, external record IDs).
uuid.uuid3(namespace, name) UUID v3 MD5 hash of namespace UUID + name string Yes Legacy compatibility with systems explicitly requiring MD5-based UUID v3 (prefer uuid5).
uuid.uuid1() UUID v1 Host MAC address + Gregorian timestamp No (leaks host MAC & timestamp) Legacy distributed systems requiring node-based timestamps (avoid in public APIs).