Generate a UUID
Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.
A record needs an identifier that nobody has to coordinate, and sometimes the same input must always give the same one.
import uuid
u = uuid.uuid4()
print(len(str(u)), u.version, len(u.hex))
print(uuid.uuid4() == uuid.uuid4())
print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))
print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com") == uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))
print(uuid.UUID("CFBFF0D1-9375-5685-968C-48CE8B15AE17"))36 4 32
False
cfbff0d1-9375-5685-968c-48ce8b15ae17
True
cfbff0d1-9375-5685-968c-48ce8b15ae17uuid4 fills the identifier with 122 random bits from os.urandom, so collisions are not a practical concern and no state is shared between machines. uuid5 hashes a namespace and a name with SHA-1, so the same pair always returns the same value, which suits deriving a stable ID from a URL or an email. The module is described in the uuid documentation. str gives the hyphenated text and hex the 32 characters without hyphens, and a parsed value is normalized to lowercase.
uuid1 embeds the MAC address and a timestamp, which leaks both, so prefer uuid4. A random UUID has no order, which makes it a poor primary key for a B-tree index that wants sequential inserts. Python 3.14 added uuid7 for time-ordered values. UUIDs are identifiers, not secrets; use the secrets module for tokens.