Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys
Python UUID gives you 128-bit identifiers that are unique without a central counter, so different servers can create IDs independently. Learn which version to pick (random uuid4, name-based uuid5, time-ordered uuid7), how to parse and store them, the privacy problem with uuid1, and how each one performed as a database primary key in our test.
- Python UUID support lives in the standard
uuidmodule;uuid.uuid4()is the right default for random IDs. uuid5always returns the same ID for the same namespace and name, which makes it ideal for deterministic keys.- In our run,
uuid1().nodeequalled this computer’s hardware node ID, so uuid1 can leak which machine created a record. - Inserting 300,000 rows took 0.67 s with random uuid4 text keys, 0.53 s with time-ordered keys and 0.30 s with integer keys in SQLite.
Auto-increment IDs work well until you have several databases, offline clients, or services that create records before they reach the database. They also reveal how many orders or users you have. A UUID (Universally Unique Identifier) solves both problems: any machine can create one at any time, and the chance of two being equal is negligible. Python UUID handling is built into the standard library, but the version you pick affects privacy, sorting and database performance.
We ran every example on Python 3.13.6. The uuid7() function was added in Python 3.14, which we did not have, so we built a version 7 UUID by hand following the RFC 9562 layout and noted the 3.14 call alongside it.
What is a UUID?
A UUID is a 128-bit number, usually written as 32 hexadecimal digits in five groups, such as c6c23dad-be2a-5229-84f3-2403be22baee. The format is defined by RFC 9562 (which replaced RFC 4122 in 2024). Some bits record the version, which tells you how the rest was generated, and the variant, which identifies the standard layout. Microsoft calls the same thing a GUID.
uuid4: random UUIDs
import uuid
u = uuid.uuid4()
u.version, u.variant # (4, 'specified in RFC 4122')
len(str(u)), len(u.bytes) # (36, 16)
# 1,000,000 uuid4 values: all unique
# about 1.52 microseconds per call
Version 4 fills 122 bits with random data from the operating system’s secure random source. It reveals nothing about when or where it was created, needs no coordination, and is fast: about 1.5 microseconds each in our test, and a million of them had no duplicates. For most applications, this is the version to use.
Anatomy of a UUID
c6c23dad-be2a-5229-84f3-2403be22baee
^ ^
| variant bits (8, 9, a or b)
version digit (5)
The first digit of the third group is always the version, so you can tell a v4 (xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx) from a v7 (xxxxxxxx-xxxx-7xxx-xxxx-xxxxxxxxxxxx) at a glance. The first digit of the fourth group encodes the variant. The uuid.UUID object exposes these as .version and .variant, plus .hex, .int, .bytes and .urn.
uuid5 and uuid3: the same name always gives the same ID
a = uuid.uuid5(uuid.NAMESPACE_DNS, "stackquora.com")
b = uuid.uuid5(uuid.NAMESPACE_DNS, "stackquora.com")
a == b # True
a # UUID('c6c23dad-be2a-5229-84f3-2403be22baee')
uuid.uuid3(uuid.NAMESPACE_URL, "https://example.com/a")
# UUID('a257f385-897f-3805-9a3a-db29b1f92977')
Name-based UUIDs hash a namespace and a name. Version 5 uses SHA-1 and version 3 uses MD5; prefer 5. The output is deterministic, so two systems can compute the same ID for “user email x” or “product SKU y” without talking to each other, and re-importing the same data never creates duplicates. The standard namespaces are NAMESPACE_DNS, NAMESPACE_URL, NAMESPACE_OID and NAMESPACE_X500, or you can use any UUID as your own namespace. Do not use name-based UUIDs for secrets: anyone who knows the name can compute the ID. Hashing in general is covered in our Python hashlib guide.
uuid1 and the privacy problem
u1 = uuid.uuid1()
u1.version # 1
u1.node == uuid.getnode() # True
Version 1 combines a timestamp with the computer’s node ID, normally its network card’s MAC address. Our check confirmed that the node field in a freshly generated uuid1 matched this machine’s node ID, so every uuid1 identifies the computer that created it. The Python documentation warns about exactly this privacy issue. Avoid uuid1 for anything exposed to users; if you want time ordering, use version 7 instead.
uuid7: time-ordered UUIDs
# Python 3.14 and later:
# u = uuid.uuid7()
# Manual version 7 for Python 3.13 (RFC 9562 layout, for illustration):
def uuid7_manual():
ms = int(time.time() * 1000) # 48-bit Unix time in milliseconds
rnd = random.getrandbits(74)
val = (ms << 80) | (0x7 << 76) | ((rnd >> 62) << 64) | (0b10 << 62) | (rnd & ((1 << 62) - 1))
return uuid.UUID(int=val)
# IDs from later milliseconds always sorted after earlier ones: True
# uuid4 values sorted into creation order: False
# timestamp recoverable from the first 48 bits: True
Version 7 puts a millisecond timestamp in the first 48 bits and random data in the rest. That makes IDs roughly sortable by creation time while keeping them unpredictable and free of hardware details. In our test, IDs created in later milliseconds always sorted after earlier ones, while uuid4 values sorted in a random order. The creation time can be read back from the ID, which is useful for debugging but means a v7 reveals when a record was created. Our hand-written function uses random for brevity; production code should use the standard library’s uuid7() on 3.14 or a maintained package, which use a secure random source.
Which UUID version should you use?
| Version | Based on | Use for |
|---|---|---|
| 4 | Random | The default: request IDs, public IDs, most primary keys |
| 7 | Time + random | Database primary keys on large tables, logs, event streams |
| 5 | SHA-1 of namespace + name | Deterministic IDs, deduplication, idempotent imports |
| 3 | MD5 of namespace + name | Only for compatibility with existing v3 data |
| 1 | Time + MAC address | Avoid: leaks the machine identity |
Parsing and validating UUIDs
s = "12345678-1234-5678-1234-567812345678"
uuid.UUID("{12345678-1234-5678-1234-567812345678}") == uuid.UUID(s) # True (braces)
uuid.UUID("12345678123456781234567812345678") == uuid.UUID(s) # True (no dashes)
uuid.UUID(s.upper()) == uuid.UUID(s) # True (any case)
str(uuid.UUID(s.upper())) # '12345678-1234-5678-1234-567812345678' (normalised lower case)
uuid.UUID(s).version # None (not an RFC 9562 layout)
uuid.UUID("not-a-uuid") # ValueError: badly formed hexadecimal UUID string
uuid.UUID() accepts several spellings and normalises them, so convert incoming strings with it before comparing or storing. Catch ValueError to reject invalid input from URLs and forms. Note that a well-formed hex string is not necessarily a standard UUID: our sample had no valid version, so .version was None. Check u.version in (4, 7) if you only accept certain versions.
String, hex, bytes and integer forms
str(u) # 36 characters with dashes
u.hex # 32 characters, no dashes
u.bytes # 16 raw bytes
u.int # a 128-bit integer
u.urn # 'urn:uuid:...'
The text form is convenient but takes 36 bytes, more than twice the 16-byte binary form. Databases with a native UUID type (PostgreSQL’s uuid, SQL Server’s uniqueidentifier) store 16 bytes; in MySQL, store BINARY(16) rather than CHAR(36) for large tables. In JSON and URLs, the standard string is the safest. JavaScript cannot hold a 128-bit integer as a normal number, so never send u.int to a browser; see our JavaScript BigInt guide for why.
UUIDs as database primary keys
| Primary key (SQLite, 300,000 inserts) | Time |
|---|---|
| Random uuid4, as text | 0.67 s |
| Time-ordered (version 7 layout), as text | 0.53 s |
| Integer, auto-assigned | 0.30 s |
Database indexes are sorted structures. Random uuid4 keys land in random positions, so every insert touches a different part of the index, which costs more page splits and cache misses as tables grow. Time-ordered keys arrive in nearly sorted order and append to the end of the index, like integers do. In our in-memory SQLite test, uuid4 inserts took about 2.2 times as long as integers and time-ordered keys about 1.8 times; on disk-based databases with indexes larger than memory, the gap is typically much bigger. Integers remain the fastest and smallest key; our auto increment guide compares them across databases, and SQL indexes explained covers why insert order matters.
Tip: a common pattern is an integer primary key for joins and a uuid4 or uuid7 column, with a unique index, as the public ID used in URLs and APIs.
How unique is unique?
A uuid4 has 122 random bits, about 5.3 undecillion possible values. You would need to generate roughly 2.7 quintillion of them before the chance of even one duplicate reached 50 percent. In practice, duplicates come from bugs, not chance: copying IDs between records, seeding a random generator with a fixed value in tests, or cloned virtual machines generating version 1 IDs with the same node and clock. If a duplicate would be harmful, keep a unique constraint in the database anyway.
UUIDs and security
- Not a password or token. uuid4 is hard to guess, but use
secrets.token_urlsafe()for session tokens and reset links, which is what thesecretsmodule is for; our Python random guide explains whyrandommust never be used for secrets. - Not authorisation. An unguessable ID in a URL does not replace checking that the user may see the record.
- Information leaks. uuid1 reveals the machine, uuid7 reveals the creation time, and uuid5 can be recomputed by anyone who knows the name.
Final thoughts
Python UUID support covers every common need with a single module. Use uuid4() by default, uuid5() when the same input must always map to the same ID, and version 7 (built in from Python 3.14) when IDs are database keys or should sort by time. Avoid uuid1 because it exposes the machine, parse every incoming ID with uuid.UUID(), and store UUIDs in a native or 16-byte binary column when tables get large. In our tests those choices made the difference between privacy leaks and safe IDs, and between random and nearly sequential inserts.
Frequently asked questions
How do I generate a UUID in Python?
Import the uuid module and call uuid.uuid4() for a random UUID. Convert it with str() for a 36-character text form, or use the hex attribute for 32 characters without dashes.
What is the difference between uuid4 and uuid7?
uuid4 is entirely random. uuid7 starts with a millisecond timestamp followed by random bits, so IDs sort roughly by creation time, which makes them friendlier to database indexes.
Is uuid4 unique enough for primary keys?
Yes. With 122 random bits, a collision is practically impossible. The bigger concern for primary keys is insert performance on large tables, where time-ordered IDs or integers are faster.
Why should I avoid uuid1?
uuid1 includes the network address of the computer that created it, so every ID reveals the machine. Use uuid4 for random IDs or uuid7 for time-ordered ones instead.
How do I check if a string is a valid UUID in Python?
Pass it to uuid.UUID inside a try block. It raises ValueError for badly formed input. Then check the version attribute if you only accept certain versions.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.