Python uuid — uuid4, uuid5, Namespaces, and Parsing
Programs constantly need identifiers that no other part of the system has already used: a row key, a file name, a token for a job that runs later. Coordinating a central counter for every one of those is fragile, and reusing a name is worse. The uuid module solves both shapes of the problem with no package to install: uuid4 makes a random identifier, and uuid5 makes the same identifier every time from a namespace and a name. This guide takes those two generators in turn, then the older hash form, the standard namespaces, the string form, the fields inside a UUID, parsing, and comparison.
Written November 17, 2026 · Tested with Python 3.12.3 · 13 min read
- The main program: a random UUID with uuid4
- A repeatable UUID: uuid5 from a namespace and a name
- The standard namespaces, and uuid3 beside uuid5
- The string form: hyphens at 8-4-4-4-12
Written November 17, 2026
Tested with Python 3.12.3
What this guide is
The uuid module provides immutable UUID objects and the generator functions defined by RFC 4122. A UUID is a 128-bit value, usually written as 32 hexadecimal digits grouped by hyphens. The module offers four generators: one based on the host and the current time, one based on an MD5 hash, one random, and one based on a SHA-1 hash. This guide covers the random and hash-based generators in code, because their behavior is the behavior most programs rely on, and covers the time-based generator in prose. A UUID object itself is only an identifier: it stores the value, converts it to strings, bytes, and integers, and compares and hashes by that value.
The main program: a random UUID with uuid4
uuid4 builds a UUID from random data, so two calls give two different values. Because the value itself changes on every run, the useful things to state about a fresh uuid4 result are its properties, and those properties are stable: the result is a UUID object, its version is 4, its variant is the one specified in RFC 4122, and its string form is 36 characters long, with a 32-character hex form and 16 bytes behind both:
import uuid
u = uuid.uuid4()
print(type(u).__name__, isinstance(u, uuid.UUID))
print(u.version, u.variant)
print(len(str(u)), len(u.hex), len(u.bytes))
print(uuid.uuid4() != uuid.uuid4())
print(isinstance(str(u), str))
The exact output:
UUID True
4 specified in RFC 4122
36 32 16
True
True
That set of properties is the whole contract. A program stores or sends the string form, the hex form, or the bytes, and rebuilds an equal object from any of them later, as the parsing section below shows. Nothing about a version 4 value can be derived from the value itself: it carries no timestamp, no host information, and no sequence, which is why it is the default choice when a program needs a fresh identifier and has nothing meaningful to derive one from.
A repeatable UUID: uuid5 from a namespace and a name
uuid5 takes the opposite approach. It hashes a namespace UUID together with a name using SHA-1, so the same pair always produces the same UUID, on any machine and in any run. The standard library documents one worked example, the DNS namespace with the name python.org, and the value it produces is fixed:
import uuid
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'))
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'))
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') == uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'))
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org').version)
print(str(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')) == '886313e1-3b8a-5372-9b90-0c9aee199e5d')
The exact output:
886313e1-3b8a-5372-9b90-0c9aee199e5d
886313e1-3b8a-5372-9b90-0c9aee199e5d
True
5
True
Repeatability is the point. A program that imports the same named records more than once can derive each record's identifier from its name and get the same identifier on the second import, so the import updates the existing record instead of creating a duplicate. The version is 5, marking the SHA-1 name-based form. Nothing is stored and nothing is coordinated: the identifier is a pure function of the namespace and the name, and any other program that knows both computes the same value.
The standard namespaces, and uuid3 beside uuid5
The module defines four namespace constants, one each for names that are DNS names, URLs, ISO object identifiers, and X.500 distinguished names. Each constant is itself a UUID, and the four values are fixed. The older name-based generator, uuid3, takes the same two arguments but hashes with MD5 instead of SHA-1, so the same namespace and name give a different UUID with version 3. Changing either the name or the namespace changes the result under both generators:
import uuid
print(uuid.NAMESPACE_DNS)
print(uuid.NAMESPACE_URL)
print(uuid.NAMESPACE_OID)
print(uuid.NAMESPACE_X500)
print(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org'))
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'))
print(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') == uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'))
print(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org').version, uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org').version)
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com'))
print(uuid.uuid5(uuid.NAMESPACE_URL, 'python.org'))
The exact output:
6ba7b810-9dad-11d1-80b4-00c04fd430c8
6ba7b811-9dad-11d1-80b4-00c04fd430c8
6ba7b812-9dad-11d1-80b4-00c04fd430c8
6ba7b814-9dad-11d1-80b4-00c04fd430c8
6fa459ea-ee8a-3ca4-894e-db77e160355e
886313e1-3b8a-5372-9b90-0c9aee199e5d
False
3 5
cfbff0d1-9375-5685-968c-48ce8b15ae17
7af94e2b-4dd9-50f0-9c9a-8a48519bdef0
Two rules follow from that output. First, pick the namespace that matches the kind of name being hashed: a domain name belongs in the DNS namespace and a URL in the URL namespace, and the last two lines show that the same text in two namespaces is two different identifiers. Second, pick one generator for a set of identifiers and stay with it, because uuid3 and uuid5 never agree on the same input. New code uses uuid5, since SHA-1 is the stronger of the two hashes; uuid3 remains for matching identifiers that an existing system already derived with it. A program can also build its own namespace by generating one UUID and keeping it as a constant, which keeps its derived identifiers separate from everyone else's.
The string form: hyphens at 8-4-4-4-12
Converting a UUID to a string with str gives the canonical form: 32 hexadecimal digits in five groups of 8, 4, 4, 4, and 12, joined by hyphens at fixed positions. The full string is 36 characters. The hex attribute is the same digits with no hyphens, and the urn attribute is the string form with the urn:uuid: prefix:
import uuid
u = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
s = str(u)
print(s)
print(len(s))
print([len(part) for part in s.split('-')])
print([i for i, ch in enumerate(s) if ch == '-'])
print(u.hex)
print(u.urn)
The exact output:
886313e1-3b8a-5372-9b90-0c9aee199e5d
36
[8, 4, 4, 4, 12]
[8, 13, 18, 23]
886313e13b8a53729b900c9aee199e5d
urn:uuid:886313e1-3b8a-5372-9b90-0c9aee199e5d
The fixed shape is what makes the string form safe to store and compare as text: every UUID string has the same length, the same hyphen positions, and lowercase digits. Two UUIDs stored as their string forms compare the same way as text as they do as objects, because the form has no optional parts. The exception is input a program receives from elsewhere, which may carry braces, a URN prefix, or no hyphens at all. Parsing, covered below, accepts all of those forms and normalizes them to the same object, so the string a program stores should be the one str produces, whatever shape the input arrived in.
Inside a UUID: fields, int, bytes, and bytes_le
A UUID exposes its value in several shapes, one for each kind of consumer. The fields attribute is a tuple of the six integer fields, in order: a 32-bit value, two 16-bit values, two 8-bit values, and a 48-bit value. The int attribute is the whole value as a single 128-bit integer. The bytes attribute is the 16 bytes in big-endian order, while bytes_le holds the first three fields in little-endian order and the rest unchanged, so the two byte forms differ in their first eight bytes. The individual field attributes sit beside the derived clock_seq value, and variant and version report the layout and the generation method:
import uuid
u = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
print(u.fields)
print(u.int)
print(list(u.bytes))
print(list(u.bytes_le))
print(u.variant, u.version)
print(u.time_low, u.time_mid, u.time_hi_version, u.clock_seq, u.node)
The exact output:
(2288194529, 15242, 21362, 155, 144, 13859559153245)
181289448026289383154478846676280385117
[136, 99, 19, 225, 59, 138, 83, 114, 155, 144, 12, 154, 238, 25, 158, 93]
[225, 19, 99, 136, 138, 59, 114, 83, 155, 144, 12, 154, 238, 25, 158, 93]
specified in RFC 4122 5
2288194529 15242 21362 7056 13859559153245
Most programs only need the string form and one of the byte or integer forms. The byte form suits a compact database column, and the integer form suits arithmetic and ordering in code that treats the identifier as a number. The field attributes matter mainly when a program interoperates with a system that stores the pieces separately, or when it reads the version off a value it received. Note that version is meaningful only for the RFC 4122 variant: a UUID built from arbitrary bytes or an arbitrary integer can report a variant for which the version carries no meaning, so a program checks the variant first when the distinction matters.
Parsing: strings, hex, bytes, and back
The UUID constructor rebuilds an object from every form the attributes produce, and from the looser forms found in text. It accepts a string of hexadecimal digits with hyphens, braces, and a URN prefix all optional, the 16 bytes as bytes, the little-endian bytes as bytes_le, the integer as int, and the six-field tuple as fields. Every one of those routes back to the same value compares equal to the original:
import uuid
u = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
print(uuid.UUID(str(u)) == u)
print(uuid.UUID(u.hex) == u)
print(uuid.UUID('{' + str(u) + '}') == u)
print(uuid.UUID(u.urn) == u)
print(uuid.UUID(bytes=u.bytes) == u)
print(uuid.UUID(bytes_le=u.bytes_le) == u)
print(uuid.UUID(int=u.int) == u)
print(uuid.UUID(fields=u.fields) == u)
The exact output:
True
True
True
True
True
True
True
True
That round trip is the working rule for storage: store whichever form the storage layer prefers, and rebuild the object on the way out, rather than passing strings and objects around mixed together. Exactly one of the constructor arguments takes part in a single call, apart from the optional version argument, which forces the variant and version bits of the result. Malformed input, such as a string that is not 32 hexadecimal digits once the optional parts are removed, raises ValueError, so code that parses identifiers from a file or a request catches that error and reports the bad value instead of letting it travel further into the program.
Equality, ordering, and hashing
UUID objects compare by value. Two objects built separately from the same input are equal, the ordering operators order by the integer value, and sorting a list of UUIDs gives a stable order. UUIDs are also hashable, with equal objects hashing equal, so they work directly as dictionary keys and set members, and a set keeps one copy of each distinct value:
import uuid
a = uuid.UUID('00000000-0000-0000-0000-000000000001')
b = uuid.UUID('00000000-0000-0000-0000-000000000002')
c = uuid.UUID('00000000-0000-0000-0000-000000000001')
print(a == c, a == b)
print(a < b, b > a, a <= c, a >= c)
print(sorted([b, a, c]))
print(hash(a) == hash(c))
labels = {a: 'first'}
print(labels[c])
print(len({a, b, c}))
The exact output:
True False
True True True True
[UUID('00000000-0000-0000-0000-000000000001'), UUID('00000000-0000-0000-0000-000000000001'), UUID('00000000-0000-0000-0000-000000000002')]
True
first
2
The dictionary lines carry the practical lesson. Because a and c are equal and hash equal, a lookup with c finds the entry stored under a, and the set built from all three holds two values, not three. A program can therefore use UUID objects themselves as keys and members throughout, with no need to convert to strings first for correctness. Converting to a string at a boundary, such as JSON or a database column, and parsing back on return preserves that behavior, because the parsed object is equal to the one that was stored.
The time-based option: uuid1
The remaining generator, uuid1, builds a UUID from the host identifier and the current time, with an optional node argument and clock sequence. It has the drawback the documentation states plainly: it may compromise privacy, since it creates a UUID containing the computer's network address. For that reason this guide gives it no worked example. A program that publishes or sends its identifiers, which is most programs, uses uuid4 for fresh identifiers and uuid5 for derived ones, and reaches for the time-based form only when a time-based identifier is specifically needed and the identifiers stay inside one system.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| A fresh identifier with nothing to derive it from | uuid4 |
Random, with no timestamp, host, or sequence information in the value |
| The same identifier from the same name, every run | uuid5 with a namespace |
A SHA-1 hash of namespace and name, so the result is a pure function of the input |
| Matching identifiers an older system derived with MD5 | uuid3 with a namespace |
The same inputs as uuid5, with the older hash and version 3 |
| A value to store or send as text | str(u) |
The canonical 36-character form, with hyphens at 8-4-4-4-12 |
| A compact value for a binary column | u.bytes |
The 16 bytes in big-endian order, and bytes_le for the little-endian field layout |
| An identifier received as text, bytes, or an integer | The UUID constructor |
Accepts the string, hex, bytes, bytes_le, int, and fields forms and returns an equal object |
Checklist
- Use
uuid4for fresh identifiers, and state or store only its string, hex, or byte form, never an assumed value. - Use
uuid5when the identifier must be repeatable, and keep the namespace and the name spelling fixed, because either one changing changes the result. - Match the namespace to the kind of name: DNS names, URLs, object identifiers, and X.500 names each have their own constant.
- Store the canonical string from
str, and parse incoming text with theUUIDconstructor instead of comparing raw input strings. - Remember that
bytesandbytes_lediffer in the first three fields, and use the matching constructor argument on the way back. - Use UUID objects directly as dictionary keys and set members, and avoid the time-based generator for identifiers that leave the machine.
Related guides on this site
- Python hashlib — Hash Text, Bytes, and Files — the hash functions the name-based generators are built on, used directly on text, bytes, and files.
- Python strings — slicing and methods — the plain string operations behind the canonical string form and its fixed hyphen positions.
- Python sqlite3 — Tables, Queries, and Transactions — storing identifiers as text or bytes in a table and reading them back.
- Python JSON — dumps, loads, and Files — sending an identifier as its string form in JSON and parsing it back into an object.
Sources
- Python Standard Library,
uuid— theUUIDclass and its attributes, theuuid1,uuid3,uuid4, anduuid5functions, the four namespace constants, the constructor forms, and the workedpython.orgexamples for the name-based generators.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.