Skip to main content

How to Generate UUID in Python

Built-in uuid module

Every Python application needs unique identifiers sooner or later, and the built-in uuid module gives you everything required without installing a single package. Call uuid.uuid4() for a random, cryptographically secure UUID in one line, or reach for uuid1(), uuid3(), and uuid5() when you need a timestamp-based or deterministic identifier instead. Below you'll find copy-paste ready code for generating a Python UUID, converting a string back into a UUID object, and the alternate generation methods Python ships with. The online uuid generator runs entirely client-side and produces cryptographically secure random identifiers.

Generate UUID in Python

uuid.uuid4()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Python

The simplest way to generate a UUID in Python is uuid.uuid4(), which uses your operating system's cryptographically secure random number generator to produce a 128-bit identifier with virtually zero chance of collision. No installation, no configuration — just import the standard library module and call the function. The online uuid generator runs entirely client-side and produces cryptographically secure random identifiers.

main.py
import uuid

my_uuid = uuid.uuid4()
print(my_uuid)
# Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in Python

Sometimes you receive a UUID as a plain string — from a form field, a JSON payload, or a config file — and need to work with it as a proper uuid.UUID object again. Python's uuid module makes this a one-liner. Use the uuid v4 generator to generate a 122-bit random UUID instantly, with one-click clipboard copy.

main.py
import uuid

my_uuid = uuid.uuid4()
my_uuid_str = str(my_uuid)

# Convert the string back into a UUID object
same_uuid = uuid.UUID(my_uuid_str)
assert my_uuid == same_uuid

Explanation

Other Options for Generating UUIDs in Python

uuid4() covers most use cases, but Python's standard library also ships three other UUID generation methods for when you need a timestamp-based or deterministic identifier instead of a random one. The java uuid page covers UUID comparison, sorting, and storage in PostgreSQL via the JDBC driver.

main.py
import uuid

# Version 1 - timestamp + MAC address, sortable by creation time
uuid1_id = uuid.uuid1()

# Version 5 - deterministic, same namespace + name always produce the same UUID
uuid5_id = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')

# Version 3 - like v5, but uses MD5 instead of SHA-1 (legacy, prefer v5)
uuid3_id = uuid.uuid3(uuid.NAMESPACE_DNS, 'example.com')

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!