On this page
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
- Avoid
uuid1()in public APIs: It embeds the host's MAC address and timestamp; useuuid4()(random) oruuid7()(time-ordered, Python 3.14+). - Don't use
uuid4()as an authentication secret: It only carries 122 bits of randomness; usesecrets.token_urlsafe(32)for API keys and session tokens. - Validate untrusted strings with
try: uuid.UUID(raw) except ValueError:: Never assume an incoming string is a valid UUID.
Common Functions
- uuid.getnode() —
getnode()— Get the hardware address as a 48-bit positive integer. - uuid.main() —
main()— Run the uuid command line interface. - uuid.uuid1() —
uuid1(node=None, clock_seq=None)— Generate a UUID from a host ID, sequence number, and the current time. - uuid.uuid3() —
uuid3(namespace, name)— Generate a UUID from the MD5 hash of a namespace UUID and a name. - uuid.uuid4() —
uuid4()— Generate a random UUID. - uuid.uuid5() —
uuid5(namespace, name)— Generate a UUID from the SHA-1 hash of a namespace UUID and a name. - uuid.uuid6() —
uuid6(node=None, clock_seq=None)— Similar to :func:uuid1but where fields are ordered differently for improved DB locality. - uuid.uuid7() —
uuid7()— Generate a UUID from a Unix timestamp in milliseconds and random bits. - uuid.uuid8() —
uuid8(a=None, b=None, c=None)— Generate a UUID from three custom blocks.
Classes & Objects
- uuid.bytes_ — bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes (Methods:
.capitalize(),.center(),.count(),.decode(),.endswith(),.expandtabs()) - uuid.Enum — Create a collection of name/value pairs.
- uuid.int_ — int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - uuid.SafeUUID — An enumeration.
- uuid.UUID — Instances of the UUID class represent UUIDs as specified in RFC 4122. (Methods:
.bytes(),.bytes_le(),.clock_seq(),.clock_seq_hi_variant(),.clock_seq_low(),.fields())
Constants & Attributes
uuid.MAX(UUID) =UUID('ffffffff-ffff-ffff-ffff-ffffffffffff')uuid.NAMESPACE_DNS(UUID) =UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')uuid.NAMESPACE_OID(UUID) =UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')uuid.NAMESPACE_URL(UUID) =UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')uuid.NAMESPACE_X500(UUID) =UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')uuid.NIL(UUID) =UUID('00000000-0000-0000-0000-000000000000')uuid.RESERVED_FUTURE(str) ='reserved for future definition'uuid.RESERVED_MICROSOFT(str) ='reserved for Microsoft compatibility'uuid.RESERVED_NCS(str) ='reserved for NCS compatibility'uuid.RFC_4122(str) ='specified in RFC 4122'
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/urllib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/venv Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/base64 Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/email Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/json Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mailbox Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mimetypes Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/uuid/bytes_ Linked here; shared tags: #stdlib