Python UUID Module
The uuid module provides immutable UUID objects (Universally Unique Identifiers) and the functions uuid1(), uuid3(), uuid4(), and uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
Importing the Module
import uuid
Generating UUIDs
UUID4 (Random)
This is the most commonly used version. It generates a random UUID.
import uuid
id = uuid.uuid4()
print(id)
# Output example: 8f1496c6-3347-479f-b725-225538192726
print(type(id)) # <class 'uuid.UUID'>
UUID1 (Host & Time)
Generates a UUID from a host ID, sequence number, and the current time.
id = uuid.uuid1()
print(id)
UUID3 and UUID5 (Name-based)
Generate a UUID using an MD5 hash (uuid3) or SHA-1 hash (uuid5) of a namespace UUID and a name.
# uuid3 (MD5)
print(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org'))
# uuid5 (SHA-1) - Preferred over uuid3
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'))
Converting to String
UUID objects are not strings, but they convert easily.
id = uuid.uuid4()
str_id = str(id)
print(str_id)
Hex Representation
You can get the raw hex string (without dashes).
print(id.hex)