How to generate unique IDs in Python


Borislav Hadzhiev

Last updated: Sep 8, 2022


Photo from Unsplash

Generate unique IDs in Python #

Use the uuid.uuid4() method to generate unique IDs, e.g. unique_id = uuid.uuid4(). The uuid built-in module implements a uuid4() method that generates and returns a random ID.
import uuid print(uuid.uuid4()) # 👉️ 730ed4ba-d703-4cdf-8b30-f8399352fabb print(uuid.uuid4().int) # 👉️ 136047018022410445780946091752650147825 print(uuid.uuid4().bytes) # 👉️ b'*\xe1h**\xceC\x87\xae\x8e\x1d\x81zX\x1c\xef' print(uuid.uuid4().hex) # 👉️ 4fa066987b2c4507a949a94c1fb43f50

We used the uuid.uuid4 method to generate random IDs.
import uuid print(uuid.uuid4()) # 👉️ 730ed4ba-d703-4cdf-8b30-f8399352fabb print(uuid.uuid4()) # 👉️ 81fd808b-76a0-4ebf-9096-f45d6f7d495a print(uuid.uuid4()) # 👉️ 753237da-bb2e-460a-88bb-329cc1dc5fe4

The built-in uuid module provides immutable UUID objects and functions for generating UUIDs.

If all you need is a unique ID, you should use the uuid4() method.

You can pass the unique ID to the str() class to convert the UUID to a string of hex digits in standard form.
import uuid unique_id = uuid.uuid4() print(unique_id) # 👉️ 011963c3-7fa3-4963-8599-a302f9aefe7d print(type(unique_id)) # 👉️ <class 'uuid.UUID'> unique_id_str = str(unique_id) print(unique_id_str) # 👉️ 011963c3-7fa3-4963-8599-a302f9aefe7d print(type(unique_id_str)) # 👉️ <class 'str'>

You can access the bytes attribute of the UUID object to get the raw 16 bytes of the UUID.
import uuid unique_id_bytes = uuid.uuid4().bytes print(unique_id_bytes) # 👉️ b'\x9e\xfb\xf4Ma\xc1I\xcc\xa0[2\\\xb6\xe9\x06\x9f' # 👇️ generate UUID from 16-byte string result = uuid.UUID(bytes=unique_id_bytes) print(result) # 👉️ 9efbf44d-61c1-49cc-a05b-325cb6e9069f

The int attribute of the UUID object returns the UUID as a 128-bit integer.
import uuid unique_id_int = uuid.uuid4().int print(unique_id_int) # 👉️ 49084253960468019865244738914988538494

The hex attribute of the object returns the UUID as a 32-character lowercase hexadecimal string.
import uuid unique_id_int = uuid.uuid4().hex print(unique_id_int) # 👉️ c56fb2e760fb4d3ba6c426c00c602a55

If all you need is a random ID, use the uuid.uuid4() method.
import uuid random_unique_id = uuid.uuid4() print(random_unique_id) # 👉️ 1fafff7f-6248-41f0-8b28-1e28bb12962b
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.