Code Example
import uuid
# UUID v4 (random) - most common
id = uuid.uuid4()
print(id) # a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
print(str(id)) # string representation
# UUID v1 (time-based)
id1 = uuid.uuid1()
# UUID v5 (name-based, SHA-1)
namespace = uuid.NAMESPACE_DNS
id5 = uuid.uuid5(namespace, 'example.com')
# Always same output for same namespace+name
# UUID from string
id = uuid.UUID('a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d')
# UUID properties
print(id.hex) # a1b2c3d4e5f64a7b8c9d0e1f2a3b4c5d
print(id.bytes) # bytes representation
print(id.int) # integer representation
print(id.version) # 4
# Generate multiple
ids = [str(uuid.uuid4()) for _ in range(5)]
# NIL UUID
nil = uuid.UUID(int=0)
print(nil) # 00000000-0000-0000-0000-000000000000
# Validate (try parsing)
def is_valid_uuid(val):
try:
uuid.UUID(str(val))
return True
except ValueError:
return False
Key Points: Python uuid module provides v1 (time-based), v4 (random), v5 (name-based). Use str() for string output, .hex for no dashes.