Generate UUID4 Values with a Python Generator
This code defines a generator function that yields mock UUID4 values, allowing you to stream unique identifiers one at a time.
Python code
11 linesimport uuid
def generate_uuids(count=5):
"""Generate a stream of mock UUID4 values."""
for _ in range(count):
yield uuid.uuid4()
if __name__ == "__main__":
# Generate and print 5 UUIDs
for uid in generate_uuids(5):
print(uid)
Output
b1e2c3d4-5f6a-7b8c-9d0e-1f2a3b4c5d6e
c7d8e9f0-1a2b-3c4d-5e6f-7a8b9c0d1e2f
3f4a5b6c-7d8e-9f0a-1b2c-3d4e5f6a7b8c
9a0b1c2d-3e4f-5a6b-7c8d-9e0f1a2b3c4d
5e6f7a8b-9c0d-1e2f-3a4b-5c6d7e8f9a0b
How it works
The function uses the yield keyword, making it a generator that produces UUID4 values lazily. Each call to next() or iteration pulls a new UUID, which is memory-efficient for large counts. The uuid.uuid4() function generates a random UUID using OS-level randomness, ensuring uniqueness in most scenarios. Using a generator instead of a list avoids storing all UUIDs in memory at once, which is beneficial when dealing with large streams.
Common mistakes
- Calling `uuid.uuid4()` inside a list comprehension and then converting to a generator, losing the lazy benefit.
- Expecting the generator to be reusable; generators are one-shot and must be recreated to iterate again.
- Forgetting to import the `uuid` module, causing a NameError.
Variations
- Use `uuid.uuid4().hex` to get the UUID without hyphens.
- Convert the generator to a list with `list(generate_uuids(5))` if all values are needed at once.
Real-world use cases
- Generating unique request IDs for logging and tracing in a distributed system.
- Creating unique identifiers for database records in a batch import script.
- Streaming session tokens for user authentication in a web backend.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.