0
0
PythonHow-ToBeginner · 3 min read

How to Generate UUID in Python: Simple Guide

To generate a UUID in Python, use the uuid module and call uuid.uuid4() for a random UUID. This creates a unique identifier useful for many applications like database keys or session IDs.
📐

Syntax

The uuid module provides functions to create different types of UUIDs. The most common is uuid.uuid4(), which generates a random UUID.

  • import uuid: Imports the UUID module.
  • uuid.uuid4(): Generates a random UUID (version 4).
python
import uuid

random_uuid = uuid.uuid4()
💻

Example

This example shows how to generate and print a random UUID using uuid.uuid4(). Each time you run it, you get a new unique identifier.

python
import uuid

new_id = uuid.uuid4()
print(f"Generated UUID: {new_id}")
Output
Generated UUID: 3f9f3b7e-2d4a-4f3a-9a4f-2e3b5c6d7e8f
⚠️

Common Pitfalls

Some common mistakes when generating UUIDs include:

  • Using uuid.uuid1() without understanding it uses the computer's MAC address and timestamp, which can leak information.
  • Trying to create UUIDs by manually formatting strings, which can cause errors and duplicates.
  • Not importing the uuid module before use.
python
import uuid

# Wrong: manually creating a UUID string (not recommended)
# fake_uuid = '12345678-1234-5678-1234-567812345678'

# Right: use uuid module to generate
correct_uuid = uuid.uuid4()
print(correct_uuid)
Output
e.g. 7a1c2f3d-4b5e-4c6d-8f7a-9b0c1d2e3f4a
📊

Quick Reference

FunctionDescription
uuid.uuid1()Generates UUID using MAC address and timestamp (not fully random)
uuid.uuid3(namespace, name)Generates UUID based on MD5 hash of namespace and name
uuid.uuid4()Generates a random UUID (most common)
uuid.uuid5(namespace, name)Generates UUID based on SHA-1 hash of namespace and name

Key Takeaways

Use the built-in uuid module to generate UUIDs safely and easily.
uuid.uuid4() creates a random UUID and is the most common choice.
Avoid manually creating UUID strings to prevent errors and duplicates.
uuid.uuid1() includes hardware info and timestamp, so use with caution.
Always import the uuid module before generating UUIDs.