Unique IDs: uuid
A UUID is an ID that no other computer will ever make, without asking anyone: for database rows, files, requests, events. uuid makes them and checks them:
id: str = uuid.v4() // like "9b2c6f1e-3d4a-4f5b-8c7d-0e1f2a3b4c5d"
key: str = uuid.v7() // like "01a217a4-004f-75a4-aff6-2fac99f6d8d0"
print(uuid.valid(id))Output:
trueA UUID is a str: 32 hex digits in groups of 8-4-4-4-12, in lower case (RFC 9562). It compares, prints, goes into maps and into JSON like any text.
v4 and v7
| Function | Gives |
|---|---|
uuid.v4() | a random UUID: nothing about it can be guessed |
uuid.v7() | a UUID that starts with the time it was made: later ones sort after earlier ones |
v7 is the one for database keys and logs: new rows go at the end of an index, and sorting by ID sorts by time. The IDs one program makes always come in order, even many in the same millisecond. (The time in it can be read by anyone who sees the ID.)
v4 is the one for anything that shouldn’t tell when it was made: tokens in URLs, names of uploaded files, request IDs.
The random parts of both come from the system’s secure source, like crypto.random.
Checking
uuid.valid(text) is true for 8-4-4-4-12 hex digits, of any version, in upper or lower case:
print(uuid.valid("550e8400-e29b-41d4-a716-446655440000"))
print(uuid.valid("550E8400-E29B-41D4-A716-446655440000"))
print(uuid.valid("550e8400e29b41d4a716446655440000"))
print(uuid.valid("{550e8400-e29b-41d4-a716-446655440000}"))Output:
true
true
false
falseWithout the dashes, with braces or spaces around it, it isn’t valid. To compare UUIDs that may come in either case, compare a.lower() with b.lower().
Details
- v1 (which contains the computer’s network address) and v3 and v5 (made from names) are not available.
uuidis a built-in name, so it can’t be a variable’s name.- It is written in Luma, with
crypto.random, the clock andlpad.