uuid

str(uuid.uuid4()) is the answer most people need: 122 random bits from the operating system, formatted as 36 characters. uuid5(namespace, name) gives the same ID for the same name every time, and uuid.UUID(text) parses and validates one.

Data formatsPython 2.5+Live demo
Import
import uuid
from uuid import UUID, uuid4
Public API
UUID, uuid1, uuid3, uuid4, uuid5, getnode, SafeUUID, NAMESPACE_DNS/URL/OID/X500, RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE
Spec
RFC 4122 (3.13 docs); the 3.14 docs cite RFC 9562, which supersedes it
Format
128 bits, shown as 32 lowercase hex digits in groups 8-4-4-4-12
3.14 adds
uuid6(), uuid7(), uuid8(), NIL and MAX (docs.python.org 3.14)
CLI
python -m uuid (3.12+): prints a uuid4 by default

Demo

Live evaluation
Type a UUID in any accepted form. The result is its canonical string, its version and its variant.
Try:
Inputs
textstra UUID string
Code
import uuid
u = uuid.UUID('{6fa459ea-ee8a-3ca4-894e-db77e160355e}')
(str(u), u.version, u.variant)
Result
('6fa459ea-ee8a-3ca4-894e-db77e160355e', 3, 'specified in RFC 4122')

Braces, a urn:uuid: prefix, hyphens and upper case are all accepted; str() always gives the lowercase 8-4-4-4-12 form. The three valid cases are versions 3, 5 and 4: the version is the first digit of the third group. A wrong length raises "badly formed hexadecimal UUID string", while 32 characters that are not hex fail inside int() with its own message. Name-based UUIDs are case-sensitive: Python.org and python.org give unrelated IDs.

Members

Common patterns

A random ID
The common case: an opaque, unguessable identifier as text.
import uuid
request_id = str(uuid.uuid4())
Validate user input
UUID() raises ValueError for anything that is not 32 hex digits after removing braces, hyphens and the URN prefix.
import uuid
try:
    order_id = uuid.UUID(raw.strip())
except ValueError:
    order_id = None
A stable ID for a name
Same input, same UUID: deduplicate records or derive keys without a lookup table.
import uuid
user_key = uuid.uuid5(uuid.NAMESPACE_URL, 'https://example.com/users/42')
Store compactly
16 bytes instead of a 36-character string; UUID(bytes=...) reads it back.
import uuid
raw = some_uuid.bytes
same = uuid.UUID(bytes=raw)

Examples

1. Name-based UUID (SHA-1)
import uuid uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
Returns
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
2. Name-based UUID (MD5)
import uuid uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
Returns
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
3. A random UUID: always version 4, 36 characters
import uuid u = uuid.uuid4() (len(str(u)), u.version, u.variant)
Returns
(36, 4, 'specified in RFC 4122')
4. Parse any accepted form
import uuid uuid.UUID('{12345678-1234-5678-1234-567812345678}')
Returns
UUID('12345678-1234-5678-1234-567812345678')
5. Upper case is normalized
import uuid str(uuid.UUID('6FA459EA-EE8A-3CA4-894E-DB77E160355E'))
Returns
'6fa459ea-ee8a-3ca4-894e-db77e160355e'
6. The raw 16 bytes
import uuid uuid.UUID('00010203-0405-0607-0809-0a0b0c0d0e0f').bytes
Returns
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
7. Invalid text raises ValueError
import uuid uuid.UUID('1234')
Returns
ValueError: badly formed hexadecimal UUID string

Pitfalls

1. Comparing a UUID with a string
A UUID object never equals its own text: == with a str is simply False. Compare UUID with UUID, or str with str.
UUID == str
import uuid
uuid.UUID(int=1) == '00000000-0000-0000-0000-000000000001'
False
str(UUID) == str
import uuid
str(uuid.UUID(int=1)) == '00000000-0000-0000-0000-000000000001'
True
2. Putting a UUID straight into JSON
json does not know the UUID type. Convert with str() (or default=str).
json.dumps(UUID)
import uuid, json
json.dumps({'id': uuid.UUID(int=1)})
TypeError: Object of type UUID is not JSON serializable
str() first
import uuid, json
json.dumps({'id': str(uuid.UUID(int=1))})
'{"id": "00000000-0000-0000-0000-000000000001"}'

When to use

Use it
  • Primary keys and IDs that can be created anywhere without a central counter
  • Request, job and file names that must not collide
  • Deterministic IDs derived from a name (uuid5)
Reach for something else
  • Secret tokens and password-reset links → secrets.token_urlsafe(), which is designed for that purpose
  • Short, human-friendly codes → a counter or a short random string
  • Time-ordered database keys on 3.13 and older → uuid1 leaks the MAC address; 3.14 adds uuid7()

Notes

CPython impl
Lib/uuid.py is pure Python: the UUID class stores one 128-bit int (in __slots__) and computes every other attribute from it. uuid3/uuid5 use hashlib.md5/sha1; uuid4 is UUID(bytes=os.urandom(16), version=4)
Immutable
Assigning to any attribute raises TypeError: UUID objects are immutable. UUIDs are hashable and sort by their int value
Versions
version is 1 to 5 (3.13) and only meaningful when variant == RFC_4122; for other variants it is None

FAQ

import uuid, then uuid.uuid4() for a random one. It returns a UUID object; str(uuid.uuid4()) gives the usual 36-character text and uuid.uuid4().hex the 32 digits without hyphens.