How to create a GUID/UUID in Python

32    Asked by ranjan_3152 in Python , Asked on Jul 22, 2025

Ever wondered how to generate unique identifiers in Python? Learn how to create a GUID/UUID using Python’s built-in uuid module, which helps in generating secure and universally unique identifiers for databases, APIs, or session tokens.

Answered by Karan Trivedi

To create a GUID/UUID in Python, the easiest and most reliable way is by using the built-in uuid module. UUID stands for Universally Unique Identifier and is a 128-bit number used to uniquely identify information in computer systems. It's especially useful in scenarios where uniqueness across systems is important, such as database keys, session tokens, or file identifiers.

Here’s how you can generate a UUID in Python:

import uuid
# Generate a random UUID (version 4)
unique_id = uuid.uuid4()
print(unique_id)

This will give you a UUID that looks something like:

 e6e01b26-3859-4a75-963f-4aab6ff07b89

Types of UUIDs you can generate:

  • uuid1(): Generates a UUID based on host ID and current timestamp.
  • uuid3(): Generates a UUID based on an MD5 hash of a namespace and name.
  • uuid4(): Generates a random UUID (most commonly used).
  • uuid5(): Generates a UUID based on a SHA-1 hash of a namespace and name.

Why use UUIDs?

  • Ensures global uniqueness.
  • Safer than incremental IDs in distributed systems.
  • Easy to generate and doesn’t require a centralized authority.

When to be cautious:

  • UUIDs are longer than simple integers, so they can take up more storage space.
  • For security-sensitive applications, use version 4 UUIDs to avoid predictability.

In summary, Python makes it very simple to generate GUIDs/UUIDs using the uuid module, giving you a reliable way to create unique identifiers across applications and systems.



Your Answer

Interviews

Parent Categories