Our Products

Favicon ExtractorFavicon ExtractorFavicon GeneratorFavicon GeneratorFont GeneratorFont GeneratorRedirect CheckerRedirect CheckerLinkGoWhereLinkGoWhereHTML to MarkdownHTML to Markdown

© 2025 UUID Generator. All rights reserved.

Programming Languages

BashBashC#C#DelphiDelphiGoGoJavaJavaJavascriptJavascriptkotlinkotlinPythonPythonPHPPHPRubyRubyRustRustTypeScriptTypeScriptVB.NETVB.NET

Generating UUID in Python

Python is a high-level, interpreted programming language known for its readability and concise syntax. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability and simple syntax, notably using whitespace indentation to denote code blocks instead of braces or keywords. Python supports multiple programming paradigms, including object-oriented, imperative, functional, and procedural programming. It has a robust standard library capable of handling tasks such as file I/O, system calls, and network communication, and a vast ecosystem of third-party libraries that offer additional functionalities like scientific computing, graphical user interfaces, and web scraping.

A notable feature of Python is its dynamic typing system, which means that variables do not need to be declared with a type beforehand, and types are automatically determined at runtime based on the value assigned to the variable. Python also provides automatic memory management and garbage collection, making memory management easier and reducing the risk of memory leaks. Python is highly popular in fields such as data science, machine learning, web development, and automation scripting, with its flexibility and ease of use making it an ideal choice for both beginners and professional developers.

In Python, to generate a UUID, you can use the uuid module from the standard library. This module provides functions to generate UUIDs of different versions.

1. Generating UUID Version 1 (Time-based UUID)

UUID Version 1 is a time-based UUID, which combines the current time with a node (usually the MAC address) to generate the UUID.

import uuid

# Generate UUID Version 1
uuid_v1 = uuid.uuid1()
print(f"UUID v1: {uuid_v1}")

In this code snippet, the uuid.uuid1() function generates a Version 1 UUID. This version of UUID is unique because it includes a timestamp and a node identifier that is generated at the time of creation.

2. Generating UUID Version 3 (Name-based UUID using MD5 hash)

UUID Version 3 is a name-based UUID that utilizes the MD5 hashing algorithm. You can generate a UUID for a specific name, and as long as the name and namespace are the same, the generated UUID will also be the same.

import uuid

# Define a namespace and a name
namespace = uuid.NAMESPACE_DNS
name = 'example.com'

# Generate UUID Version 3
uuid_v3 = uuid.uuid3(namespace, name)
print(f"UUID v3: {uuid_v3}")

In this code snippet, the uuid.uuid3() function takes two arguments: a namespace and a name. It generates a UUID using the MD5 hashing algorithm.

3. Generating UUID Version 4 (Random-based UUID)

UUID Version 4 is a random-based UUID, which is entirely randomly generated, thus offering a high degree of uniqueness.

import uuid

# Generate UUID Version 4
uuid_v4 = uuid.uuid4()
print(f"UUID v4: {uuid_v4}")

In this code snippet, the uuid.uuid4() function generates a Version 4 UUID. This version of the UUID is randomly generated and does not use timestamps or node information.

4. Generating UUID Version 5 (Name-based UUID using SHA1 hash)

UUID Version 5 is similar to Version 3, but it uses the SHA1 hashing algorithm. This is also a name-based UUID, used to generate a stable UUID.

import uuid

# Define a namespace and a name
namespace = uuid.NAMESPACE_DNS
name = 'example.com'

# Generate UUID Version 5
uuid_v5 = uuid.uuid5(namespace, name)
print(f"UUID v5: {uuid_v5}")

In this code snippet, the uuid.uuid5() function takes two arguments: a namespace and a name. It generates a UUID using the SHA1 hashing algorithm.

5. Converting UUID to String and Bytes

UUIDs can be represented in different formats:

import uuid

# Generate a UUID
my_uuid = uuid.uuid4()

# As a string (default format)
uuid_str = str(my_uuid)
print(f"String format: {uuid_str}")

# As a hexadecimal string (no hyphens)
uuid_hex = my_uuid.hex
print(f"Hex format: {uuid_hex}")

# As bytes (16 bytes)
uuid_bytes = my_uuid.bytes
print(f"Bytes format: {uuid_bytes}")

# Convert back from string
uuid_from_str = uuid.UUID(uuid_str)
print(f"From string: {uuid_from_str}")

6. Validating UUIDs

You can validate whether a string is a valid UUID:

import uuid

def is_valid_uuid(uuid_string):
    try:
        uuid.UUID(uuid_string)
        return True
    except ValueError:
        return False

# Test validation
print(is_valid_uuid("550e8400-e29b-41d4-a716-446655440000"))  # True
print(is_valid_uuid("invalid-uuid"))  # False

Best Practices for Python UUIDs

1. Use UUID v4 for Most Cases

import uuid

# Simple and secure
user_id = uuid.uuid4()
session_id = uuid.uuid4()

2. Store as Binary in Databases

For better performance, store UUIDs as binary (16 bytes) instead of strings (36 bytes):

import uuid
import sqlite3

# Store as BLOB
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id BLOB PRIMARY KEY)')

user_id = uuid.uuid4()
cursor.execute('INSERT INTO users (id) VALUES (?)', (user_id.bytes,))

# Retrieve and convert back
cursor.execute('SELECT id FROM users')
row = cursor.fetchone()
retrieved_uuid = uuid.UUID(bytes=row[0])
print(f"Retrieved: {retrieved_uuid}")

3. Use UUID v5 for Deterministic IDs

When you need the same input to always produce the same UUID:

import uuid

# Always generates the same UUID for the same input
namespace = uuid.NAMESPACE_URL
url = "https://example.com/user/123"

user_uuid = uuid.uuid5(namespace, url)
# Will always be: 9fe8e8c4-aaa8-5827-a654-7bb54e0f2fcb

Performance Tips

  • UUID v4 is the fastest (just random number generation)
  • UUID v1 requires MAC address lookup (slightly slower)
  • UUID v3/v5 require hashing (slowest, but still very fast)

For most applications, the performance difference is negligible.

Common Use Cases

import uuid

# Web session ID
session_token = str(uuid.uuid4())

# Database primary key
user_id = uuid.uuid4()

# Unique filename
filename = f"{uuid.uuid4()}.txt"

# Request tracking ID
request_id = uuid.uuid4()
print(f"Request ID: {request_id}")

# Idempotency key for API calls
idempotency_key = str(uuid.uuid4())