Create a UUID in Python with uuid4 and uuid7

Create a UUID in Python with uuid4 and uuid7

To create a UUID in Python, import the standard-library uuid module and call uuid.uuid4(). Convert the result with str() when you need text. Python 3.14 and later also include uuid.uuid7() for time-ordered IDs.

Create a UUID in Python with the standard library

The Python uuid module is included with Python. This example creates a random version 4 UUID:

import uuid

value = uuid.uuid4()
print(value)
print(type(value).__name__)
print(value.version)

The first line is the generated ID. The next lines are UUID and 4: the function returns a UUID object. Use str(value) for its 36-character, hyphenated text form. Use value.hex for the same value as 32 hexadecimal characters without hyphens.

text = str(value)
compact = value.hex
print(len(text), len(compact))
print(uuid.UUID(text) == uuid.UUID(compact))

These examples were checked with Python 3.12.10. The length check printed 36 32, and parsing both forms produced True. Changing the display leaves the underlying ID unchanged.

Check Python support before calling uuid7

Python 3.14 added uuid7(). Its format includes a timestamp, unlike a random v4 UUID. Check whether the runtime provides it:

import uuid

if hasattr(uuid, "uuid7"):
    print(uuid.uuid7())
else:
    print("UUID v7 requires Python 3.14 or later.")

On the Python 3.12.10 interpreter used for this guide, this printed the version message. UUID v7 generation was not executed in that check. An unguarded uuid.uuid7() call on that standard library raises AttributeError.

For a few values without changing your Python environment, the UUID Generator offers v4 and v7 in your browser. If the choice affects a database key or public URL, read the v4 versus v7 database ID guide before changing the version.

To read an existing UUID, use uuid.UUID(text). That parses the supplied value; it does not generate another random ID. To check its version, inspect parsed.version after parsing. Passing version=4 to the constructor overwrites version and variant bits, so it does not validate that the original text was v4.

Generate a batch of UUIDs and save them

  1. Choose how many values you need. Call uuid.uuid4() inside the loop so each item is generated separately.
  2. Convert each result to text before writing it to a text file.
  3. Write one UUID per line. The example below writes uuids.txt in the current working directory and replaces that file if it already exists.
  4. Read the file back and parse every line. Check the count and the version before importing the values into another system.
import uuid
from pathlib import Path

ids = [str(uuid.uuid4()) for _ in range(5)]
path = Path("uuids.txt")
path.write_text("\n".join(ids) + "\n", encoding="utf-8")

saved = path.read_text(encoding="utf-8").splitlines()
print(len(saved))
print(all(uuid.UUID(item).version == 4 for item in saved))

The local fixture saved five lines and parsed every one as v4. A small successful batch does not prove that collisions can never occur. For one value from a terminal, Python 3.12 and later also accept python -m uuid; the default is v4.

What UUID generation does not check

  • A valid UUID format does not show that the ID exists in your database or that a caller may access its record.
  • Keep a uniqueness constraint where duplicate IDs would cause a problem. Random generation reduces collision risk without making duplicates impossible.
  • A v7 UUID exposes an approximate creation time. This guide does not benchmark database indexes or test ordering across multiple processes.
  • Use Python's secrets module for password-reset tokens and similar secrets. RFC 9562 warns against treating possession of a UUID as permission to access something.
  • The runnable checks used Python 3.12.10. The v7 branch follows the Python 3.14 documentation and needs a supported runtime before it can run.

Frequently asked questions

Do I need to install a package to create a UUID in Python?

No. Python includes the uuid module. Import uuid and call uuid.uuid4() for a random version 4 UUID. UUID v7 support in the standard library starts with Python 3.14.

Why does uuid.uuid7() raise AttributeError?

The standard libraries in Python versions before 3.14 do not include uuid7(). Check your interpreter version or use hasattr(uuid, 'uuid7') before calling it. A v4 UUID is a different version, so do not silently substitute it when your system requires v7.

How do I get a UUID string without hyphens?

Use the UUID object's hex attribute, such as value.hex. It returns 32 hexadecimal characters. str(value) returns the same ID with hyphens in a 36-character string.

Does uuid.UUID(value) create a new random ID?

No. It parses an existing value into a UUID object. Call uuid.uuid4() to generate a new random UUID. Avoid passing version=4 when checking an existing version because that argument changes the version and variant bits.

Tools used in this guide

  • UUID GeneratorDeveloper Tools

    Generates random v4 and time-ordered v7 UUIDs.

More from the blog

All guides