How to create a GUID/UUID in Python ?

To create a GUID/UUID (Globally Unique Identifier/Universally Unique Identifier) in Python, use the built-in uuid module. Below are the methods and examples for generating different types of UUIDs:

1. Generate a Random UUID (Version 4)

The most common method, using cryptographically secure random numbers:

import uuid

# Generate a random UUID (version 4)
guid = uuid.uuid4()
print(guid)  # Example: "f47ac10b-58cc-4372-a567-0e02b2c3d479"

2. Generate a UUID Based on Host/Time (Version 1)

Uses the host’s MAC address and current timestamp. Not recommended for sensitive applications (exposes MAC address):

guid = uuid.uuid1()
print(guid)  # Example: "6fa459ea-ee8a-11e3-ac10-0800200c9a66"

3. Generate Namespace-Based UUIDs

a) UUID3 (MD5 Hash)

namespace = uuid.NAMESPACE_DNS  # Predefined namespace (e.g., DNS, URL, OID)
name = "example.com"
guid = uuid.uuid3(namespace, name)
print(guid)  # Example: "6fa459ea-ee8a-11e3-ac10-0800200c9a66"

b) UUID5 (SHA-1 Hash)

guid = uuid.uuid5(uuid.NAMESPACE_URL, "https://example.com")
print(guid)  # Example: "886313e1-3b8a-5372-9b90-0c9aee199e5d"

4. Convert UUID to String

a) Hyphenated String (Default)

guid_str = str(uuid.uuid4())
print(guid_str)  # "f47ac10b-58cc-4372-a567-0e02b2c3d479"

b) Without Hyphens

guid_hex = uuid.uuid4().hex
print(guid_hex)  # "f47ac10b58cc4372a5670e02b2c3d479"

Key Notes

  1. Version 4 (Random): Best for most use cases (privacy-safe, no MAC address exposure).
  2. Version 1 (Time/Host): Avoid if privacy is a concern (contains MAC address).
  3. Namespace UUIDs (v3/v5): Deterministic UUIDs for the same namespace/name pair.
  4. Uniqueness: UUIDs are not guaranteed to be unique, but the probability of collision is negligible.

Example Workflow

import uuid

def generate_secure_uuid():
    return uuid.uuid4()

# Generate and use a UUID
user_id = generate_secure_uuid()
print(f"User ID: {user_id}")
# Output: "User ID: f47ac10b-58cc-4372-a567-0e02b2c3d479"

Use Cases

  • Database Keys: Use uuid4() for unique primary keys.
  • Session Tokens: Generate secure tokens with uuid4().
  • Namespace Identifiers: Use uuid3()/uuid5() for reproducible identifiers (e.g., file names).

Security Considerations

  • Use uuid4() for security-sensitive applications (randomness is cryptographically secure in Python 3.7+).
  • Avoid uuid1() if exposing MAC addresses or timestamps is a concern.

Leave a Reply

Your email address will not be published. Required fields are marked *