PYTHON

Python uuid Module: Syntax, Usage, and Examples

The uuid module helps you generate UUIDs, short for “Universally Unique Identifiers,” which are values designed to be extremely unlikely to collide. You’ll often use UUIDs as IDs for users, orders, files, sessions, or anything that needs a reliable unique label.


How to Use the uuid Module

You import the uuid module, then call one of its UUID generator functions like uuid4().

import uuid

new_id = uuid.uuid4()
print(new_id)

That prints something like:

7c5f6c52-1f1d-4c8e-9a2a-4bfa9dfe2c9d

A UUID is a real Python object, not just a string. You can convert it to a string when you want to store it or send it over the network.

import uuid

user_id = uuid.uuid4()
user_id_str =str(user_id)

print(user_id_str)
print(type(user_id))
print(type(user_id_str))

Common UUID generators

The uuid module gives you multiple ways to generate identifiers, and each one has a different “source” for its randomness or uniqueness.

import uuid

print(uuid.uuid1())# time + device info
print(uuid.uuid3(uuid.NAMESPACE_DNS,"mimo.org"))# name-based (MD5)
print(uuid.uuid4())# random
print(uuid.uuid5(uuid.NAMESPACE_DNS,"mimo.org"))# name-based (SHA-1)

You won’t use all of these every day, but they’re useful in different situations, especially if you need consistent IDs from the same input.


When to Use the uuid Module

The uuid module shines anytime you need an ID that is safe to generate without asking a database for permission first.

1) Creating IDs for database records

Auto-increment IDs like 1, 2, 3 are simple, but they can leak information like how many users you have. UUIDs don’t tell that story.

You can generate a UUID before inserting a record:

import uuid

order = {
"id":str(uuid.uuid4()),
"status":"pending"
}

2) Generating safe filenames

If users upload files, two people can upload profile.png and one upload overwrites the other. UUIDs solve that.

import uuid

filename =f"{uuid.uuid4()}.png"
print(filename)

3) Creating tokens for links and sessions

Password reset links, invite links, email verification links, all of these need “unguessable” values. UUIDs are a solid option for that.

import uuid

reset_token = uuid.uuid4().hex
print(reset_token)

That .hex version removes the dashes and gives you a clean string.

4) Creating stable identifiers from names

Sometimes you want the same input to always produce the same output. That’s where name-based UUIDs help.

Example: generating an ID for a product category name.

import uuid

category_name ="winter-jackets"
category_id = uuid.uuid5(uuid.NAMESPACE_URL, category_name)

print(category_id)

You’ll get the same UUID every time you run that with the same namespace and string.


Examples of the uuid Module

Here are a few practical examples that show how UUIDs fit into real projects.

Example 1: Assigning UUIDs to users in a simple app

Imagine a small Python app that keeps user data in memory.

import uuid

users = []

defcreate_user(name):
    user = {
"id":str(uuid.uuid4()),
"name": name
    }
    users.append(user)
return user

print(create_user("Amina"))
print(create_user("Leo"))

Now each user has a unique ID that won’t conflict with anyone else.


Example 2: Using UUIDs as dictionary keys

UUID strings make great keys in dictionaries, especially when you store objects by ID.

import uuid

messages = {}

msg_id =str(uuid.uuid4())
messages[msg_id] = {"text":"Hi there!","read":False}

print(messages[msg_id])

This pattern shows up in caching, storing temporary sessions, and in-memory queues.


Example 3: Creating a unique upload path

Here’s a common pattern when storing uploads by date and a UUID.

import uuid
from datetimeimport date

today = date.today().isoformat()
file_path =f"uploads/{today}/{uuid.uuid4()}.jpg"

print(file_path)

If you later move to cloud storage, the same idea still works.


Example 4: Generating the same ID from the same input

Name-based UUIDs are predictable in a good way. Great for things like syncing data across systems.

import uuid

namespace = uuid.NAMESPACE_DNS
project_name ="demo-project"

project_id_1 = uuid.uuid5(namespace, project_name)
project_id_2 = uuid.uuid5(namespace, project_name)

print(project_id_1)
print(project_id_2)
print(project_id_1 == project_id_2)

This prints the same value twice, and the final line is True.


Learn More About the uuid Module

UUIDs look simple, but a few details matter if you want to use them well.

UUID versions explained (quick and practical)

The version is the “strategy” used to create the UUID.

  • UUID1: based on time and hardware-related data
  • UUID3: name-based using MD5 hashing
  • UUID4: random, most common choice
  • UUID5: name-based using SHA-1 hashing

In most apps, uuid4() is the default pick because it’s random and easy.

Using .hex for cleaner strings

The normal string version of a UUID includes dashes. Sometimes that’s fine, sometimes it’s annoying.

import uuid

value = uuid.uuid4()
print(str(value))# with dashes
print(value.hex)# no dashes

.hex is handy for URLs, tokens, and compact storage.

Converting strings back to UUID objects

If you stored a UUID in a file or database as a string, you can recreate the UUID object like this:

import uuid

stored_id ="7c5f6c52-1f1d-4c8e-9a2a-4bfa9dfe2c9d"
real_uuid = uuid.UUID(stored_id)

print(real_uuid)
print(type(real_uuid))

That can be useful for validation, formatting, or comparisons.

Comparing UUIDs

UUID objects compare nicely with each other.

import uuid

a = uuid.uuid4()
b = uuid.uuid4()

print(a == b)# almost always False

If you compare strings, make sure the formatting matches. A UUID string with dashes is different from its .hex version.

UUIDs vs random numbers

A random integer can work as an ID, but it’s easier to collide by accident, especially if you generate lots of values.

UUIDs are built for this exact job, and they are widely used across systems, databases, and APIs.

When you might not want a UUID

UUIDs are great, but they’re not always the perfect choice.

  • They’re longer than simple numeric IDs
  • They don’t sort nicely by creation time (UUID4 is random)
  • They can make some database indexes bigger

If you need sortable IDs, people sometimes use different approaches like ULIDs, time-based IDs, or database-generated IDs. Still, UUIDs remain one of the simplest and most reliable options in Python.


Summary

The uuid module gives you a clean way to generate unique identifiers without relying on a database counter. Use uuid4() for random IDs, use .hex when you want compact strings, and use uuid5() when you need the same input to always produce the same ID. Once you start generating IDs for users, uploads, and links, this module quickly becomes a favorite tool in your Python toolbox.