Random application IDs
Create opaque identifiers for records, requests, or resources without coordinating a central counter.
Python · Module
Python’s uuid module provides immutable UUID objects and functions for generating UUIDs across RFC 9562 versions. It supports parsing and constructing UUIDs from text, bytes, fields, or integers.
The module supplies immutable UUID objects and factory functions for several RFC 9562 UUID versions. Use uuid4() for a random identifier, or construct UUID values from supported representations such as text, bytes, fields, or an integer.
class uuid.UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=<SafeUUID.unknown>)| Name | Type | Description |
|---|---|---|
hex / bytes / bytes_le / fields / int | str | bytes | tuple[int, ...] | int | A UUID value supplied as hexadecimal text, bytes, little-endian bytes, fields, or a 128-bit integer; the constructor also accepts version and related optional arguments documented on the page. |
UUID objects from the UUID class and UUID values from the module’s version-specific factory functions.
import uuid
request_id = uuid.uuid4()
print(request_id)
print(request_id.hex)Creates a random UUID and prints its canonical text form plus its 32-character hexadecimal form.
Create opaque identifiers for records, requests, or resources without coordinating a central counter.
Derive a repeatable identifier from a stable namespace and name.
Parse or serialize identifiers at API and storage boundaries.
uuid4() generates a random UUID using a cryptographically secure method. It is the usual choice for opaque application identifiers when no deterministic relationship to a namespace and name is needed.
Follow-up: How would you create the same identifier repeatedly from a namespace and name? Use uuid5(namespace, name), which derives the UUID from a SHA-1 name hash.
UUID values are immutable objects. They can be created from a hexadecimal string, big-endian or little-endian bytes, fields, or a 128-bit integer, and expose representations such as str, bytes, and int.
Follow-up: What is the difference between bytes and bytes_le? bytes uses big-endian order, while bytes_le interprets the UUID fields in little-endian order.
uuid3() and uuid5() generate name-based UUIDs from a namespace UUID and a name. uuid3() uses MD5, while uuid5() uses SHA-1; the same inputs produce the same UUID.
Follow-up: Which is generally preferable for new name-based identifiers? uuid5(), because the documentation presents it as the SHA-1 variant and MD5 is an older hash choice.
UUIDuuid1uuid3uuid4uuid5uuid6uuid7uuid8