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:
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:
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:
Validating a UUID#
To validate incoming inputs safely, handle ValueError:
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:
Best Practices#
- Always use
str(uuid_obj)when serializing to JSON: The standardjson.dumps()cannot serializeuuid.UUIDinstances directly unless converted to a string or handled by Pydantic / dataclasses. - Store as binary or native UUID in databases: If using PostgreSQL with SQLAlchemy, use
postgresql.UUID(as_uuid=True)for optimal indexing efficiency. - Format vs Injection: String validation verifies syntactic correctness. Always combine validation with parameterized database queries.