How to Generate a UUID in Python
By SimpleTools24Published 3 min read
To generate a UUID in Python, import the standard uuid module and call uuid.uuid4() for a random UUID: str(uuid.uuid4()) gives a string like '1b4e28ba-2fa1-4d2b-883f-0016d3cca427'. Python 3.14 added uuid.uuid7() for time-ordered UUIDs, and uuid.uuid5() creates deterministic UUIDs from a namespace and a name. No third-party package is needed for any of these.
In this guide
Random UUIDs With uuid4()
import uuid
u = uuid.uuid4()
print(u) # 1b4e28ba-2fa1-4d2b-883f-0016d3cca427
print(type(u)) # <class 'uuid.UUID'>uuid4() returns a UUID object, not a string. It's built from os.urandom(), a cryptographically secure source, with the version and variant bits set for version 4. What is UUID v4 explains the structure.
Converting Between Representations
| Need | Code | Example result |
|---|---|---|
| Hyphenated string | str(u) | '1b4e28ba-2fa1-4d2b-883f-0016d3cca427' |
| 32 hex digits | u.hex | '1b4e28ba2fa14d2b883f0016d3cca427' |
| 16 bytes (big-endian) | u.bytes | b'\x1bN(\xba/...' |
| Integer | u.int | A 128-bit integer |
| URN | u.urn | 'urn:uuid:1b4e28ba-...' |
| Version | u.version | 4 |
u.bytes_le gives the little-endian byte order used by Microsoft GUIDs, useful when exchanging binary values with .NET or SQL Server.
Parsing a UUID String
import uuid
def parse_uuid(text: str) -> uuid.UUID | None:
try:
return uuid.UUID(text)
except ValueError:
return None
parse_uuid('{1B4E28BA-2FA1-4D2B-883F-0016D3CCA427}') # accepts braces and uppercase
parse_uuid('1b4e28ba2fa14d2b883f0016d3cca427') # accepts no hyphensuuid.UUID() is lenient about braces, the urn:uuid: prefix, hyphens and case. If you need to enforce one exact format, compare str(parsed) with the input, or use a regex. How to validate a UUID covers both approaches.
Time-Ordered UUIDs With uuid7() (Python 3.14+)
import uuid
u7 = uuid.uuid7()
print(u7.version) # 7Version 7 UUIDs begin with a Unix timestamp in milliseconds, so they sort roughly by creation time, which is friendlier to database indexes. Python 3.14 also added uuid6(), uuid8() and the uuid.NIL and uuid.MAX constants. On older Python versions, use a third-party package for v7. How to generate UUID v7 compares options across languages.
Deterministic UUIDs With uuid5()
import uuid
uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
# always the same value for the same namespace and name
uuid.uuid5(uuid.NAMESPACE_URL, 'https://example.com/products/42')Name-based UUIDs are useful when the same input must always map to the same ID, such as deduplicating URLs or generating stable IDs from natural keys. uuid3() does the same with MD5; v5 (SHA-1) is generally preferred. UUID v3 vs v5 explains the difference.
Avoid uuid1() for New Code
uuid.uuid1() includes a timestamp and, by default, a node value derived from the machine's network hardware address when available. That can leak information about where and when an ID was made. Prefer uuid4() or uuid7() unless you need v1 for compatibility.
Using UUIDs in Frameworks
- Django:
models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False). Pass the function, notuuid.uuid4(), or every row gets the same value. - SQLAlchemy: use the
Uuidtype withdefault=uuid.uuid4. - Pydantic: annotate fields as
uuid.UUIDfor automatic validation. - JSON: convert to
str(u)before serialising; the standardjsonmodule doesn't handle UUID objects.
The Django note is worth repeating: passing default=uuid.uuid4() evaluates once at import time, which is a classic source of duplicate IDs.
Generating UUIDs Without Code
For quick test data, the UUID v4 generator creates up to 1,000 UUIDs in your browser and can format them with quotes for pasting into a Python list. To inspect a UUID you've been given, the UUID decoder shows its version, variant and, for time-based versions, the embedded timestamp.
Common Mistakes
- Comparing strings to UUID objects.
uuid.uuid4() == '1b4e...'is always False. Convert one side:str(u) == textoru == uuid.UUID(text). - Storing as text in PostgreSQL when a native
uuidcolumn is available. Drivers such as psycopg handleuuid.UUIDvalues directly. - Assuming ordering.
uuid4()values have no meaningful order; useuuid7()or a timestamp column for chronology. - Using UUIDs as secrets. For tokens, use
secrets.token_urlsafe()instead.
Generating Many UUIDs
import uuid
ids = [str(uuid.uuid4()) for _ in range(1000)]Generation is fast; a thousand UUIDs take a negligible amount of time. For writing them to a file:
from pathlib import Path
Path('ids.txt').write_text('\n'.join(ids))Command-Line One-Liners
Python 3.12 added a command-line interface to the uuid module:
python -m uuid # prints a random UUID (v4 by default)
python -m uuid -u uuid5 -n @dns -N example.comHandy for shell scripts when you don't want to write a file.
Frequently Asked Questions
How do I get a UUID as a string in Python?
str(uuid.uuid4()), or uuid.uuid4().hex for 32 characters without hyphens.
Is uuid4() secure?
It uses os.urandom(), so it's random enough for identifiers. For secrets, use the secrets module.
Which Python version has uuid7()?
Python 3.14 and later.
Why do all my Django rows have the same UUID?
You probably wrote default=uuid.uuid4() instead of default=uuid.uuid4.
Summary
uuid.uuid4() for random IDs, uuid.uuid7() on 3.14+ for time-ordered ones, uuid.uuid5() for deterministic ones. Convert with str, .hex, .bytes or .int, and pass functions, not values, as defaults.
Related tools
Sources
- uuid — UUID objects according to RFC 9562 – Python documentation (opens in a new tab)
Related articles
- Generate a UUID in JavaScriptcrypto.randomUUID() in browsers and Node.js, the uuid package for other versions, and why Math.random() snippets are a bad idea.
- UUID v3 vs v5How namespace-and-name UUIDs work, why v5 is preferred over v3, and practical uses for deterministic IDs.
- Validate a UUID in CodePractical validation in JavaScript and Python, plus notes for Java and C#, and how strict your checks should be.