Complete reference for generating, validating, and formatting UUIDs using Python’s built-in uuid module — covers uuid1, uuid3, uuid4, uuid5, and uuid7 (built into the standard library since Python 3.14).
Quick Start
Generate a Random UUID (v4) in Python
Python’s standard library includes the uuid module — no installation needed. The most common use case is generating a random UUID v4:
Python
import uuid
# Generate a random UUID (version 4)
my_uuid = uuid.uuid4()
print(my_uuid)
# 550e8400-e29b-41d4-a716-446655440000
print(str(my_uuid)) # as string
print(my_uuid.hex) # no hyphens, 32 chars
print(str(my_uuid).upper()) # uppercase
💡
uuid.uuid4() is the right default
For 95% of use cases — API IDs, session tokens, database keys where you don’t need time-ordering — uuid.uuid4() is exactly what you want. It uses os.urandom() internally, which is cryptographically secure.
All Versions
Every UUID Version in Python
Version
Python Call
Use Case
v1 (Time-based)
uuid.uuid1()
Legacy systems needing timestamp + MAC. Leaks machine identity — avoid in user-facing apps.
v3 (MD5 name-based)
uuid.uuid3(namespace, name)
Deterministic IDs from a name. Use v5 instead (MD5 is broken).
v4 (Random)
uuid.uuid4()
General purpose. The default choice for most applications.
v5 (SHA-1 name-based)
uuid.uuid5(namespace, name)
Deterministic IDs from a name — same input always gives same UUID.
v7 (Unix timestamp)
Built in since Python 3.14: uuid.uuid7()
Time-ordered UUIDs for database primary keys. On older versions, see the package option below.
Python — Deterministic UUID (v5)
import uuid
# Same namespace + name ALWAYS produces the same UUID
namespace = uuid.NAMESPACE_DNS
my_uuid = uuid.uuid5(namespace, ‘example.com’)
print(my_uuid)
# cfbff0d1-9375-5685-968c-48ce8b15ae17 (always the same)
UUID v7
UUID v7 in Python (2026 Recommended for DB Keys)
Since Python 3.14 (released October 2025), the standard library generates UUID v7 directly with uuid.uuid7(). Python 3.14 also added uuid.uuid6() and uuid.uuid8().
On Python 3.13 or older, install a backport package instead:
Terminal
pip install uuid7
Python
from uuid_extensions import uuid7, uuid7str
my_uuid = uuid7()
print(my_uuid) # time-ordered, sortable UUID
# Or as a string directly
my_uuid_str = uuid7str()
⚠️
Check your Python version
Run python –version. On Python 3.14 or newer, use the built-in uuid.uuid7(). On older versions, use the uuid7 package shown above (or the uuid6 package).
Validation
Validate a UUID String in Python
To check whether a string is a properly formatted UUID, wrap the constructor in a try/except block:
Python
import uuid
def is_valid_uuid(value: str) -> bool:
try:
uuid.UUID(str(value))
return True
except (ValueError, AttributeError, TypeError):
return False
is_valid_uuid(‘550e8400-e29b-41d4-a716-446655440000’) # True
is_valid_uuid(‘not-a-uuid’) # False
# Check the version of a parsed UUID
u = uuid.UUID(‘550e8400-e29b-41d4-a716-446655440000’)
print(u.version) # 4
Conversion
Python UUID to String (and String to UUID)
In Python, a UUID is an object, not a plain string. Python UUID conversion is simple: Use str() to turn it into the normal 36-character text, and uuid.UUID() to turn text back into an object. The constructor accepts upper or lower case, with or without hyphens, with curly braces, and with the urn:uuid: prefix.
Python
import uuid
u = uuid.uuid4()
# UUID object -> string
text = str(u) # ‘f47ac10b-58cc-4372-a567-0e02b2c3d479’
plain = u.hex # ‘f47ac10b58cc4372a5670e02b2c3d479’ (no hyphens)
upper = str(u).upper() # uppercase version
# string -> UUID object (all of these give the same UUID)
uuid.UUID(‘f47ac10b-58cc-4372-a567-0e02b2c3d479’)
uuid.UUID(‘F47AC10B58CC4372A5670E02B2C3D479’)
uuid.UUID(‘{f47ac10b-58cc-4372-a567-0e02b2c3d479}’)
uuid.UUID(‘urn:uuid:f47ac10b-58cc-4372-a567-0e02b2c3d479’)
One common error: json.dumps() cannot handle a UUID object and raises TypeError: Object of type UUID is not JSON serializable. Convert it first with str(u), or pass default=str:
Python
import json, uuid
data = {“id”: uuid.uuid4()}
print(json.dumps(data, default=str))
Formats
Python UUID Hex, Bytes and Integer Formats
The same Python UUID can be read in several formats. This is useful when you store IDs in a database column, send them over a network or compare them with other systems.
Python
import uuid
u = uuid.UUID(‘f47ac10b-58cc-4372-a567-0e02b2c3d479’)
u.hex # 32 hex characters, no hyphens
u.bytes # 16 raw bytes (big-endian) – good for BINARY(16) columns
u.bytes_le # 16 bytes in Microsoft GUID byte order
u.int # one 128-bit integer
u.urn # ‘urn:uuid:f47ac10b-…’
u.version # 4
# Build a UUID back from each format
uuid.UUID(hex=u.hex)
uuid.UUID(bytes=u.bytes)
uuid.UUID(int=u.int)
If you see a GUID from .NET that looks “scrambled” compared with Python, it is usually the byte order. Read our GUID generator page for more on GUIDs, or paste any value into the UUID decoder to see its version and parts.
Short IDs
Short UUIDs in Python
A standard UUID is 36 characters long. If you need a short Python UUID for URLs, you can encode the same 16 bytes in Base64. The result is 22 characters and still holds the full 128-bit value, so it can be turned back into the original UUID.
Python
import base64, uuid
u = uuid.UUID(‘f47ac10b-58cc-4372-a567-0e02b2c3d479′)
short = base64.urlsafe_b64encode(u.bytes).rstrip(b’=’).decode()
print(short) # ‘9HrBC1jMQ3KlZw4CssPUeQ’ (22 characters)
# back to the full UUID
original = uuid.UUID(bytes=base64.urlsafe_b64decode(short + ‘==’))
Another option is the third-party shortuuid package (pip install shortuuid), which also produces 22-character IDs using a readable alphabet. Avoid cutting a UUID with str(u)[:8]: an 8-character slice has only 32 bits and collisions become likely once you have tens of thousands of IDs. See UUID length for how length affects uniqueness.
Frameworks
UUIDs in Django, FastAPI & SQLAlchemy
Django Model Field
import uuid
from django.db import models
class Order(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
FastAPI + Pydantic
from pydantic import BaseModel
from uuid import UUID, uuid4
class Item(BaseModel):
id: UUID = uuid4()
name: str
SQLAlchemy
import uuid
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import UUID
class Order(Base):
__tablename__ = ‘orders’
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
FAQ
Python UUID FAQ
Python’s uuid module is part of the standard library since Python 2.5, so no installation is needed. Just import uuid and call uuid.uuid4() for a random UUID. This works in any standard Python 3 installation with zero external dependencies.
uuid.uuid4() returns a UUID object with useful properties like .hex, .int, .bytes, and .version. str(uuid.uuid4()) converts it to the standard 36-character hyphenated string format. Use the UUID object when you need to inspect version or variant bits, and the string form for storage, display, or JSON serialization.
Yes. Python’s uuid4() uses os.urandom() internally, which draws from the operating system’s cryptographically secure random number source. It is safe to use in contexts requiring unpredictability, though a UUID alone should still not be used as a password or authentication secret.
Python 3.14 and newer include it in the standard library: import uuid, then call uuid.uuid7(). On Python 3.13 or older, install a backport such as the uuid7 package (pip install uuid7) and use from uuid_extensions import uuid7.
Call str() on the UUID object, for example str(uuid.uuid4()). This gives the standard 36-character form with hyphens. Use the .hex attribute if you need the 32-character form without hyphens.
Pass the string to uuid.UUID(), for example uuid.UUID(“f47ac10b-58cc-4372-a567-0e02b2c3d479”). It accepts upper or lower case, missing hyphens, curly braces and the urn:uuid: prefix, and raises ValueError if the text is not a valid UUID.
Encode the 16 UUID bytes with base64.urlsafe_b64encode(u.bytes).rstrip(b”=”) to get a 22-character ID that can be decoded back. The shortuuid package is another option. Do not simply slice the first 8 characters, because that removes most of the uniqueness.