Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 149 ยท Modules and the Standard Library

uuid, Random IDs and Unique Keys

Generate unique identifiers in Python with uuid1, uuid4, uuid5 and uuid7, create secure tokens with secrets, and learn when collisions matter and which ID to use.

Almost every program eventually needs to name things: an order, a user, an uploaded file, a session, a password-reset link. The simplest names are counters (1, 2, 3...), and for a single small database that works. But counters break down as soon as two machines create records independently, when you don't want strangers to guess the next ID, or when you need a name that is stable for the same input. For these jobs Python's standard library offers uuid for identifiers and secrets for unguessable tokens.

In this lesson you'll learn what a UUID is, the differences between versions 1, 4, 5 and 7, how to turn them into strings, integers and bytes, how likely a collision really is, how to generate secure tokens, and how to choose the right kind of ID for a job.

What is a UUID?

A UUID (universally unique identifier) is a 128-bit number, usually written as 32 hexadecimal digits in five groups: 123e4567-e89b-12d3-a456-426614174000. The format is defined by an internet standard (RFC 9562), so every language and database understands it. Two properties make UUIDs useful:

  • You can generate them anywhere without asking anyone. No central counter, no database round trip, so servers, phones and offline apps can all create IDs independently.
  • The chance of two being equal is negligible for the versions that use random bits.

In Python a UUID is an immutable uuid.UUID object, which you can compare, hash and use as a dictionary key. The most common choice is version 4, which is almost entirely random:

Python Creating and inspecting a UUID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same UUID can be written several ways: str(u) gives the dashed text form you store in JSON or a URL, u.hex the 32-digit form without dashes, u.bytes 16 raw bytes (the compact form for a binary database column), and u.int a very large integer. Always convert user input with uuid.UUID(text); an invalid string raises ValueError, which is exactly the validation you want at the edge of your program.

The versions

The version number tells you how the other bits are filled in.

Version Function Built from Typical use
1 uuid.uuid1() timestamp + machine (MAC) address rarely; leaks the time and machine
3 uuid.uuid3(ns, name) MD5 hash of a namespace and a name legacy; prefer 5
4 uuid.uuid4() 122 random bits the general default
5 uuid.uuid5(ns, name) SHA-1 hash of a namespace and a name a stable ID for the same input
7 uuid.uuid7() millisecond timestamp + random bits database primary keys (sortable)

uuid7() was added in Python 3.14; on older versions use a third-party package or uuid4().

Version 4: random

Version 4 is the right answer when you just need "a new unique ID" and nothing about the ID needs to mean anything. It carries 122 random bits (6 bits are fixed to mark the version and variant) and is built from the operating system's secure random source.

Versions 5 and 3: names that always give the same ID

Sometimes you want the same ID every time for the same thing: for example, one stable ID per web address, per email address, or per product code, without keeping a lookup table. A name-based UUID hashes a namespace (itself a UUID) together with a name. The same inputs always give the same UUID, and different inputs give different UUIDs:

Python Stable IDs with uuid5

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python provides four ready-made namespaces (NAMESPACE_DNS, NAMESPACE_URL, NAMESPACE_OID, NAMESPACE_X500). For your own system, derive one namespace UUID once and keep using it. Note that uuid5 is a hash, not a secret: anyone who knows the name and namespace can compute the ID, so never use it as a token.

Version 1: time and machine

uuid1() mixes the current time with a node identifier (often the machine's network address). That makes it unique across machines, but it reveals when and where it was made, which can be a privacy problem, and consecutive IDs look alike. It still appears in older systems, but new code should prefer version 4 or 7.

Version 7: random but sortable

Random IDs have one cost: when you use them as a primary key, new rows land at random places in the database index, which is slower than appending in order. Version 7 fixes that by putting a millisecond timestamp in the leading bits and random bits after it, so IDs created later sort after IDs created earlier:

Python uuid7 sorts by creation time (Python 3.14+)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because the first 48 bits hold the time, a UUIDv7 is also not fully private: anyone can read when it was created. If that matters, use version 4.

How likely is a collision?

"Unique" really means "so unlikely to repeat that you can ignore it". With 122 random bits there are about 5.3 x 10^36 possible version-4 UUIDs. The chance that any two among n random IDs match follows the birthday problem: about nยฒ / (2 x 2^122).

Python The birthday math for uuid4

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A billion version-4 UUIDs still have a repeat chance around 10^-19, so a duplicate is far less likely than a hardware fault. But the second table is a warning: if you shorten IDs (say, to 8 hex digits), collisions become likely quickly. Shortening a UUID shortens its safety margin. If you need short public codes, check the uniqueness against your database and retry on a clash.

Secure tokens with secrets

A UUID is meant to be unique, not necessarily unguessable: its structure is public, and version 1 and 7 are partly predictable. For things that act like passwords, such as reset links, API keys, session IDs and email confirmation codes, use the secrets module, which draws from the operating system's cryptographic random source:

Python Tokens, comparison and short codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

token_urlsafe(n) returns about 1.3 x n characters from n random bytes, and 32 bytes (256 bits) is a common, comfortable choice. If you pass no argument, Python picks a default size for you. compare_digest takes the same time whether the strings differ at the first character or the last, which prevents attackers from measuring the difference and guessing a token one character at a time. Never use random.random() or uuid1() for tokens.

Choosing an ID

You need... Use
A unique ID for a database row, nothing else uuid.uuid4(), or uuid.uuid7() if the key index matters
An ID that sorts by creation time uuid.uuid7()
The same ID every time for the same input uuid.uuid5(namespace, name)
A reset link, API key or session token secrets.token_urlsafe(32)
A short code a human types secrets.choice over a safe alphabet, plus a uniqueness check
A single database, IDs shown in URLs, enumeration doesn't matter an auto-increment integer is fine
The ID of some content (a file) a hash of the bytes, see below

For content-addressed names, hash the bytes themselves with hashlib. Two files with identical content get identical names, which is how many caches and Git itself avoid storing duplicates:

Python
import hashlib

data = b"hello world"
print(hashlib.sha256(data).hexdigest()[:16])   # b94d27b9934d3e08

Common mistakes

  • Comparing UUID objects with strings. uuid.UUID(...) == "..." is False. Convert one side first.
  • Storing UUIDs as long text columns. Many databases have a native UUID type (or 16 bytes of binary), which is smaller and faster than 36 characters of text.
  • Using a UUID as a secret. A UUID4 from uuid.uuid4() is random, but it's meant as an ID. Generate secrets with secrets, so you don't depend on the version rules.
  • Truncating and hoping. A shorter ID is only safe with a uniqueness check.
  • Using uuid1() in public URLs. It exposes a timestamp and often the machine's MAC address.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function gives the same UUID every time for the same namespace and name?

    uuid3 and uuid5 hash a namespace and a name, so identical inputs always produce the same UUID. The others use random or time-based bits.
  2. 2. Why is uuid7 often preferred over uuid4 for database primary keys?

    Time-ordered keys are appended near the end of an index instead of landing at random places, which is usually faster. The embedded time also means the ID is not private.
  3. 3. You need a password-reset link token. What should you use?

    secrets uses the operating system's cryptographic random source. uuid1 and uuid5 are predictable or computable, and the random module is not secure.
  4. 4. What does uuid.UUID("not-a-uuid") do?

    The constructor validates its input, which makes it a handy check for IDs that arrive in requests.
  5. 5. You shorten random IDs to 8 hexadecimal digits to make them friendlier. What changes?

    8 hex digits give only 2^32 values, so the birthday effect makes repeats likely quickly. Check uniqueness and retry, or keep the full length.

Summary

  • A UUID is a 128-bit identifier you can generate anywhere without coordination; Python represents it as uuid.UUID with .hex, .bytes, .int and .version.
  • uuid4() is the default random ID; uuid7() (Python 3.14+) is random but time-sortable; uuid5(namespace, name) gives a stable ID for the same input; uuid1() leaks time and machine information.
  • Version-4 collisions are astronomically unlikely, but truncating an ID destroys that guarantee.
  • Use secrets.token_urlsafe() and secrets.compare_digest() for anything that acts like a password.
  • For content, hash the bytes; for tiny single-database apps, an integer counter is still fine.

Next: Excel Files with openpyxl, where you read and write spreadsheets from Python.