Python ships with a uuid module in its standard library, so generating UUIDs needs no third-party packages. The most common choice is uuid4(), which returns a random version 4 UUID suitable for database keys, request IDs, and file names.
The examples below work in Python 3 and cover the random, time-based, and name-based generators, plus how to validate a UUID string.
Generate a random UUID (v4)
uuid4() is the go-to function. It returns a UUID object; call str() on it (or use .hex) when you need a string to store or send.
import uuid
# Random UUID (version 4)
new_id = uuid.uuid4()
print(new_id) # e.g. 9b2e4f1a-3c6d-4e58-9f0a-1b2c3d4e5f60
print(str(new_id)) # same value as a string
print(new_id.hex) # 32 hex chars, no hyphensTime-based (v1) and name-based (v5) UUIDs
Use uuid1() for a time-based UUID and uuid5() for a deterministic, name-based UUID. uuid5() always returns the same value for the same namespace and name.
import uuid
# Time-based UUID (version 1)
print(uuid.uuid1())
# Name-based UUID (version 5) — deterministic
print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))Validate a UUID string in Python
Parse the string with uuid.UUID(); it raises ValueError if the input is not a valid UUID. This is more reliable than a regular expression.
import uuid
def is_valid_uuid(value: str) -> bool:
try:
uuid.UUID(value)
return True
except ValueError:
return False
print(is_valid_uuid("9b2e4f1a-3c6d-4e58-9f0a-1b2c3d4e5f60")) # True
print(is_valid_uuid("not-a-uuid")) # FalseFrequently asked questions
- Which UUID version should I use in Python?
- uuid4() (random) is the best default. Use uuid1() if you need time-based IDs and uuid5() when you need the same UUID for the same input.
- Do I need to install anything to use uuid in Python?
- No. The uuid module is part of the Python standard library, so it is available in any Python 3 installation.
- How do I get a UUID without hyphens in Python?
- Use the .hex attribute, e.g. uuid.uuid4().hex, which returns the 32-character form without hyphens.
