How to Generate UUIDs in Python
UUIDs let producers assign record identifiers without coordinating a central counter. Python’s uuid module generates random version 4 identifiers and parses UUID text. Use the version that matches your API and keep stable IDs wherever a test depends on them.
Generate values with the standard library
Use uuid4() to create an independent value. Keep the UUID object while working in Python and call str() when serializing it for a JSON API. The canonical representation uses five groups of hexadecimal digits. In a UUID v4, the first character of the third group is 4.
A generated ID is useful for a temporary record or event sent by multiple workers. Create it once when the logical event is created and persist it alongside that event. A retry should reuse the same ID when the receiver uses it for deduplication.
from uuid import UUID, uuid4
event_id = uuid4()
payload = {"eventId": str(event_id)}
parsed = UUID(payload["eventId"])
assert parsed == event_id
assert parsed.version == 4Give fixtures stable identifiers
Generate a few UUIDs once and save them in the fixture if tests compare exact JSON output. Random values inside snapshot tests produce unrelated diffs. A test that checks only shape or uniqueness can generate fresh IDs and assert their properties instead.
UUID v5 derives a stable value from a namespace and a name. It can be useful for mapping an external record to a repeatable internal ID. Agree on the namespace and normalize names consistently. Changing case or Unicode normalization changes the input and therefore the resulting ID.
from uuid import NAMESPACE_URL, uuid5
identifier = uuid5(NAMESPACE_URL, "https://example.com/items/42")
assert identifier.version == 5Handle invalid IDs at the boundary
UUID(text) can raise ValueError for malformed input. Parse it where you read the request and check its version only if your contract requires one. Avoid passing version=4 as a validation shortcut because that argument can set version bits rather than checking the supplied value.
A database uniqueness constraint still matters. It catches accidental reuse and repeated imports even if random collisions are unlikely. Use a separate timestamp to sort records by creation time.
Frequently asked questions
- Is a UUID a secret?
- An identifier identifies a record. Use authentication and authorization to decide who can access it.
- Can I generate a batch here?
- The UUID generator produces up to 100 random v4 identifiers as newline-separated text.