On this page
  1. uuid
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Deterministic Content / Resource IDs with uuid5
  7. 2. Compact Formats (.hex, .bytes) for Storage
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

uuid

Prev: urllib | Up: stdlib_module | Next: venv
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — uuid
Tags: #public #python3 #stdlib


Import

import uuid

Overview

Generates and parses RFC 4122 / RFC 9562 Universally Unique Identifiers (uuid4 random, uuid5 deterministic SHA-1 namespace, uuid7 time-ordered in Python 3.14+). Use uuid4() for unguessable random IDs, uuid5() for reproducible content-derived IDs, and uuid7() (when available) for database-friendly sortable primary keys.

Quick Start

import uuid

uid = uuid.uuid4()
parsed = uuid.UUID(str(uid))
assert parsed == uid and parsed.version == 4

det = uuid.uuid5(uuid.NAMESPACE_DNS, "wispsy.com")
assert det == uuid.uuid5(uuid.NAMESPACE_DNS, "wispsy.com")

Implementation Walkthrough

1. Deterministic Content / Resource IDs with uuid5

Generate identical UUIDs across runs and machines from a fixed namespace UUID and canonical name:

import uuid

APP_NS = uuid.UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8")

def record_id(kind: str, key: str) -> str:
    return str(uuid.uuid5(APP_NS, f"{kind}:{key}"))

assert record_id("user", "ada") == record_id("user", "ada")
assert record_id("user", "ada") != record_id("user", "grace")

2. Compact Formats (.hex, .bytes) for Storage

import uuid

u = uuid.uuid4()
assert len(u.hex) == 32      # 32-char string without hyphens
assert len(u.bytes) == 16    # 16 raw bytes for compact SQLite/binary storage
assert uuid.UUID(bytes=u.bytes) == u

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes