Developer Documentation
Python
Updated September 18, 2026

Generate a UUID in Python

Generate, format, parse, and validate RFC 4122/9562 UUIDs in Python using the built-in uuid module.

Python provides robust native support for Universally Unique Identifiers through the standard library's uuid module. Because it is part of Python's standard distribution, no third-party installations (pip install) are required for core UUID v1, v3, v4, and v5 operations.

Quick Start#

Generate a cryptographically secure random UUID v4 using Python's standard library:

Python
1import uuid23# Generate a random UUID (version 4)4id_val = uuid.uuid4()56print(id_val)7# Output: 3d3b7d18-8f83-4a16-9b16-6415f33367f089print(type(id_val))10# Output: <class 'uuid.UUID'>

The returned object is an instance of uuid.UUID, which encapsulates the 128-bit integer and provides multiple formatting representations.

Formats and Representations#

Python's UUID object provides straightforward properties for exporting to different representations:

Python
1import uuid23u = uuid.uuid4()45# 1. Canonical 36-character string with hyphens6canonical = str(u)7print("Standard:", canonical)8# "3d3b7d18-8f83-4a16-9b16-6415f33367f0"910# 2. 32-character hexadecimal string without hyphens11compact_hex = u.hex12print("Hex:", compact_hex)13# "3d3b7d188f834a169b166415f33367f0"1415# 3. URN format16urn = u.urn17print("URN:", urn)18# "urn:uuid:3d3b7d18-8f83-4a16-9b16-6415f33367f0"1920# 4. Raw 16-byte binary buffer (for databases or binary storage)21raw_bytes = u.bytes22print("Bytes length:", len(raw_bytes))  # 162324# 5. Raw 128-bit integer25integer_val = u.int26print("128-bit Int:", integer_val)

Parsing a UUID from a String#

To parse any valid UUID string (with or without hyphens or URN prefix), pass it to the uuid.UUID constructor:

Python
1import uuid23raw_input = "3d3b7d18-8f83-4a16-9b16-6415f33367f0"45# Parse string into UUID object6parsed_uuid = uuid.UUID(raw_input)78# Verify version and variant9print("Version:", parsed_uuid.version)  # 410print("Variant:", parsed_uuid.variant)  # specified in RFC 4122/9562

Validating a UUID#

To validate incoming inputs safely, handle ValueError:

Python
1import uuid23def is_valid_uuid(val: str) -> bool:4    try:5        uuid_obj = uuid.UUID(val)6        # Ensure the string matches the canonical hex representation7        return uuid_obj.hex == val.replace("-", "").lower()8    except (ValueError, AttributeError, TypeError):9        return False1011# Tests12print(is_valid_uuid("3d3b7d18-8f83-4a16-9b16-6415f33367f0"))  # True13print(is_valid_uuid("not-a-uuid"))                              # False

UUID v7 in Python#

Python 3.14 includes native uuid.uuid7(). For current Python versions (3.9 to 3.13), install the high-performance uuid6 or uuid-utils package:

Bash
1pip install uuid6
Python
1import uuid623# Generate time-ordered UUIDv74id_v7 = uuid6.uuid7()5print("UUIDv7:", id_v7)

Best Practices#

  1. Always use str(uuid_obj) when serializing to JSON: The standard json.dumps() cannot serialize uuid.UUID instances directly unless converted to a string or handled by Pydantic / dataclasses.
  2. Store as binary or native UUID in databases: If using PostgreSQL with SQLAlchemy, use postgresql.UUID(as_uuid=True) for optimal indexing efficiency.
  3. Format vs Injection: String validation verifies syntactic correctness. Always combine validation with parameterized database queries.

References#