Generators are functions that can pause and resume execution. Here's how to use them effectively.
Basic Generators#
Yield Expressions#
Infinite Generators#
Delegating Generators#
Generator Methods#
Async Generators#
Iterator Protocol#
Utility Functions#
Practical Patterns#
Coroutines#
Memory Efficiency#
Best Practices#
Usage:
✓ Use for lazy evaluation
✓ Use for infinite sequences
✓ Use for stateful iteration
✓ Use for async data streams
Patterns:
✓ Combine with yield* for delegation
✓ Use try/finally for cleanup
✓ Handle errors appropriately
✓ Use async generators for I/O
Performance:
✓ Prefer generators for large datasets
✓ Avoid unnecessary array allocations
✓ Use take/limit for infinite generators
✓ Clean up resources in finally
Avoid:
✗ Complex control flow in generators
✗ Forgetting to handle done state
✗ Ignoring cleanup on early exit
✗ Overusing generators for simple cases
Conclusion#
Generators provide powerful iteration control with lazy evaluation. Use them for infinite sequences, stateful iteration, async data streams, and memory-efficient processing. Combine with yield* for delegation and async/await for asynchronous operations.