Using uuid in Python to Generate Unique

Posted by Afsal on 08-Aug-2025
Hi Pythonistas!
 
While working on your Python projects, you might need to generate unique identifiers.
Today, we'll explore the uuid module in Python, which provides a simple way to create Universally Unique Identifiers (UUIDs).
 
What is a UUID?
 
UUID stands for Universally Unique Identifier — a 128-bit number used to uniquely identify information.
It's like a digital fingerprint for data.
f47ac10b-58cc-4372-a567-0e02b2c3d479
Python makes generating UUIDs super easy with the built-in uuid module.
 
Why Use UUIDs?
  • Avoid primary key collisions in databases.
  • Generate unique filenames, tokens, or session IDs.
  • Track data across distributed systems.
  • Anonymize user IDs.
Unlike auto-increment IDs (1, 2, 3…), UUIDs are random and non-sequential, making them safer for public exposure.
UUIDs are also globally unique, meaning they can be generated independently across different systems without risk of duplication.
 
Versions of uuid
 
UUID1 - Generates a UUID using the host's MAC address and current timestamp.
UUID2 - Similar to UUID1 but includes POSIX UID/GID; rarely used and not implemented in Python's uuid module.
UUID3 - Generates a name-based UUID using MD5 hashing of a namespace and name.
UUID4 - Generates a completely random UUID using random or pseudo-random numbers.
UUID5 - Generates a name-based UUID using SHA-1 hashing of a namespace and name.
 
uuid.uuid1() and uuid.uuid4() are the most commonly used methods in Python.
 
Getting Started with uuid
 
>>> import uuid
>>> uuid.uuid1()
UUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')
>>> uuid.uuid4()
UUID('0f48d5cc-8757-4e51-a931-9b751e71f421')
>>>
uuid.uuid1() - ⚠️ May expose your machine’s MAC address. Use with care.
uuid.uuid4() -Secure and private. Best for most real-world uses.
 
Real-Life Examples
 
  • Unique Filenames for Uploads
  • Unique Order IDs in E-commerce
  •  Reset Password Token
  • Use UUID as Primary Key in databases
Check If a String is a Valid UUID
 
def is_valid_uuid(val):
    try:
        uuid.UUID(str(val))
        return True
    except ValueError:
        return False
 
Things to consider before using
 
  • UUIDs are longer than integer IDs — may impact storage and indexing.
  • Not great for sequential sorting (e.g., latest orders) — use with timestamps if needed.
  • For shorter unique IDs, consider hashlib, secrets, or nanoid libraries.
Summary

Feature uuid.uuid4()

  • Secure 
  • Globally Unique 
  • Easy to Use 
  • Doesnot Leaks system info
Use uuid.uuid4() when you need a safe, unique, and unguessable ID — for user IDs, filenames, tokens, orders, and more.