Generator Patterns
Common Generator Design Patterns
Generators offer versatile patterns for solving complex programming challenges efficiently.
1. Infinite Sequence Generator
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
## Example usage
fib_gen = fibonacci_generator()
for _ in range(10):
print(next(fib_gen))
2. Pipeline Generators
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
def filter_lines(lines, condition):
for line in lines:
if condition(line):
yield line
def transform_lines(lines, transformer):
for line in lines:
yield transformer(line)
Generator Composition Patterns
graph LR
A[Input Source] --> B[Generator 1]
B --> C[Generator 2]
C --> D[Generator 3]
D --> E[Final Result]
3. State Machine Generators
def simple_state_machine():
state = 'START'
while True:
if state == 'START':
yield 'Initializing'
state = 'PROCESS'
elif state == 'PROCESS':
yield 'Processing'
state = 'END'
elif state == 'END':
yield 'Completed'
break
Advanced Generator Techniques
Pattern |
Description |
Use Case |
Coroutines |
Two-way communication |
Complex state management |
Delegating Generators |
Nested generator handling |
Modular generator design |
Generator Comprehensions |
Compact generator creation |
Quick sequence generation |
4. Coroutine Generator
def coroutine_example():
received = None
while True:
received = yield received
print(f"Received: {received}")
## Example usage
coro = coroutine_example()
next(coro) ## Prime the coroutine
coro.send("Hello")
coro.send("World")
Best Practices
- Use generators for memory-efficient iteration
- Combine generators for complex data processing
- Understand generator lifecycle and memory implications
At LabEx, we emphasize mastering these generator patterns to write more efficient and elegant Python code.