uuid5 Derives Stable IDs From Namespaces
Derive deterministic identifiers with uuid5: hashing a namespace UUID with a natural key yields the same ID everywhere, so re-runs and upserts stay idempotent.
Code
import uuid
# uuid5 = 命名空间 UUID + 名称 做 SHA-1:同样输入在任何机器都得到同一 ID
ORDERS = uuid.uuid5(uuid.NAMESPACE_DNS, "orders.example.internal")
INVOICES = uuid.uuid5(uuid.NAMESPACE_DNS, "invoices.example.internal")
print("orders ns :", ORDERS)
print("invoices ns:", INVOICES)
# 从自然键派生记录 ID:重跑、重试、多副本写入都落到同一行,天然幂等
record_key = "customer-42#2026-11"
record_id = uuid.uuid5(ORDERS, record_key)
print("record id :", record_id)
print("recompute matches?", uuid.uuid5(ORDERS, record_key) == record_id)
# 不同命名空间隔离同名键;uuid.UUID 与字符串形式无损往返
other = uuid.uuid5(INVOICES, record_key)
print("namespaces differ?", record_id != other)
print("roundtrip stable?", uuid.UUID(str(record_id)) == record_id)Output
Captured from a sandboxed run of this snippet in the build pipeline.
orders ns : 78533f7f-fea6-557f-a304-ff86b0151025
invoices ns: 9780afd8-01e2-54a8-b3be-12dfa45eedd2
record id : 308e6ee3-d2cf-5e66-b87b-969b06b0e905
recompute matches? True
namespaces differ? True
roundtrip stable? TrueHow the snippet works
Module-level bindings hold the data — record_key, record_id, other — with no function scope in between.
Applying it
Running the file prints labeled results such as invoices ns:, recompute matches?, namespaces differ? — each operation’s effect is visible in the output.
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.UUID v7 GeneratorGenerate time-ordered UUID v7 identifiers (RFC 9562) with a 48-bit millisecond timestamp and random tail, ideal for sortable database keys.UUID Version DetectorValidate the 8-4-4-4-12 UUID layout and read its version (v1 to v8) and variant nibbles per RFC 9562, with full field decomposition.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `record_key`, `record_id`, `other`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.