Introduction
UUID (Universally Unique Identifier) provides unique identifiers for objects and distributed systems.
Creating UUIDs
import uuid
# Version 4 (random)
u1 = uuid.uuid4()
print(u1) # e3b0c442-98fc-1c14-9af9-6e0f5e5d7b6c
# Version 1 (timestamp + MAC)
u2 = uuid.uuid1()
# From string
u3 = uuid.UUID("e3b0c442-98fc-1c14-9af9-6e0f5e5d7b6c")
# Check validity
print(uuid.UUID("invalid")) # ValueError
Using UUIDs
import uuid
# As dictionary keys
users = {uuid.uuid4(): "Alice", uuid.uuid4(): "Bob"}
# For database primary keys
user_id = uuid.uuid4()
print(user_id.int) # Integer representation
# Short representation
print(u1.hex[:8]) # Short unique ID
Practice Problems
- Generate UUIDs for database records
- Use UUID as cache keys
- Create short unique identifiers
- Validate UUID format
- Generate version 1 UUIDs with custom node