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.

PythonData Integrity

Code

pythonsnippet
18 lines
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? True

How 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

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`.