Iterator Best Practices
Memory Efficiency
## Inefficient: Loading entire dataset
def load_entire_dataset(filename):
with open(filename, 'r') as file:
return file.readlines()
## Efficient: Iterator-based approach
def read_file_iterator(filename):
with open(filename, 'r') as file:
for line in file:
yield line.strip()
Error Handling Strategies
class SafeIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
try:
if self.index < len(self.data):
value = self.data[self.index]
self.index += 1
return value
raise StopIteration
except Exception as e:
print(f"Iteration error: {e}")
raise StopIteration
Iterator Design Patterns
Pattern |
Description |
Recommended Use |
Lazy Evaluation |
Compute values on-demand |
Large datasets |
State Machine |
Maintain complex iteration state |
Complex workflows |
Transformation |
Modify elements during iteration |
Data processing |
Composition and Chaining
def filter_iterator(iterator, condition):
for item in iterator:
if condition(item):
yield item
def transform_iterator(iterator, transform_func):
for item in iterator:
yield transform_func(item)
## Chaining iterators
numbers = range(10)
even_numbers = filter_iterator(numbers, lambda x: x % 2 == 0)
squared_numbers = transform_iterator(even_numbers, lambda x: x ** 2)
Iterator Flow Control
graph TD
A[Input Iterator] --> B{Condition Check}
B -->|Pass| C[Transform/Filter]
B -->|Fail| D[Skip]
C --> E[Yield Result]
D --> F[Next Item]
Advanced Iteration Techniques
Context Management
class ManagedIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
## Cleanup logic
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
value = self.data[self.index]
self.index += 1
return value
raise StopIteration
- Use generators for memory-efficient iterations
- Implement
__iter__()
and __next__()
carefully
- Avoid unnecessary computations
- Handle edge cases gracefully
Common Pitfalls to Avoid
- Modifying iterator during iteration
- Infinite iterations without proper termination
- Excessive memory consumption
- Ignoring error handling
itertools
module for advanced iteration
functools
for function composition
- Type hints for better code clarity
At LabEx, we emphasize writing clean, efficient, and maintainable iterator implementations that follow these best practices.