Skip to content

#314: Sortable GUIDs With UUID V7

One of the new features in Python 3.14 is the support for version 7 of UUID. This means we can get a built-in support for collision free and sortable unique identifiers without the need for additional packages. Let us see how we can use them.

Create version 7 UUIDs

We do not need to install any packages and can directly import the uuid module to access the version 7 function:

>>> from uuid import uuid7
>>> for i in range(10):
...     print(uuid7())
...
019ba88e-ede9-70bc-a1c2-1c4d8e01cb9f
019ba88e-ede9-70bc-a1c2-1c4e9d152f8b
019ba88e-ede9-70bc-a1c2-1c4f3d79af51
019ba88e-ede9-70bc-a1c2-1c500c2f2db3
019ba88e-ede9-70bc-a1c2-1c51ccbda1a6
019ba88e-ede9-70bc-a1c2-1c52462cb1e0
019ba88e-ede9-70bc-a1c2-1c537770920d
019ba88e-ede9-70bc-a1c2-1c5497a45314
019ba88e-ede9-70bc-a1c2-1c556c9b216c
019ba88e-ede9-70bc-a1c2-1c56e125e366

We can see that the identifiers we generate have a large part that is similar. In this part is the UNIX timestamp of the creation time encoded. That way we get the sortable keys and keep the randomness – albeit limited.

Version 4 is totally random

As comparison, the generated identifiers for version 4 are random and we have no clue about the order in which the keys were generated:

>>> from uuid import uuid4
>>> for i in range(10):
...     print(uuid4())
...
daa01320-372c-44f7-9534-c10b431e3992
7da1c58a-8094-4149-a574-c46bd1d5f096
f7b56495-e4c7-4e4a-9292-078fe4449834
de41251f-7816-469a-a4e6-96c36a7b0295
6d7c20d1-bd85-4808-a137-11a1b4bda3da
78436ff5-43c7-464f-9e0a-7945f75c6688
b8e6df21-eb77-4407-aed4-4a9f18b25cd8
c9c024dd-7832-40a1-8603-6fa90519b64e
bc65e1d0-9d04-453b-abcd-6107d1e83563
439cedad-e191-4a98-b704-604ac1380c8e

Support for older versions of Python

There are a few packages on PYPI.org that offer support for version 7 in older Python versions. However, not all packages are correct. The package uuid7 generates the identifiers based on an outdated draft of the specification. While the code on GitHub is fixed, the package was not updated and still has the wrong algorithm in it.

You can try other packages or go to the uuid implementation of Python 3.14 and copy the code into your project. Make a note that this copy can be replaced when you move to Python 3.14 or newer.

Conclusion

If you need identifiers that are random but still offer a way to sort them in order of their creation, then version 7 of UUID is a great help. You get all the benefits of UUIDs and only need to change the function you call from uuid4() to uuid7().