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.
import uuid from uuid import UUID, uuid4
Demo
import uuid u = uuid.UUID('{6fa459ea-ee8a-3ca4-894e-db77e160355e}') (str(u), u.version, u.variant)
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
import uuid request_id = str(uuid.uuid4())
import uuid try: order_id = uuid.UUID(raw.strip()) except ValueError: order_id = None
import uuid user_key = uuid.uuid5(uuid.NAMESPACE_URL, 'https://example.com/users/42')
import uuid raw = some_uuid.bytes same = uuid.UUID(bytes=raw)
Examples
Pitfalls
import uuid uuid.UUID(int=1) == '00000000-0000-0000-0000-000000000001'
import uuid str(uuid.UUID(int=1)) == '00000000-0000-0000-0000-000000000001'
import uuid, json json.dumps({'id': uuid.UUID(int=1)})
import uuid, json json.dumps({'id': str(uuid.UUID(int=1))})
When to use
- 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)
- 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
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.