Custom Iterator Design
Advanced Iterator Implementation
Creating Complex Iterators
class FibonacciIterator:
def __init__(self, max_count):
self.max_count = max_count
self.current = 0
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.current < self.max_count:
result = self.a
self.a, self.b = self.b, self.a + self.b
self.current += 1
return result
raise StopIteration
## Usage example
fib_iterator = FibonacciIterator(10)
for num in fib_iterator:
print(num)
Iterator Design Patterns
Iterator Types
Iterator Type |
Description |
Use Case |
Finite Iterator |
Stops after a predefined number of iterations |
Generating limited sequences |
Infinite Iterator |
Continues generating values indefinitely |
Continuous data streams |
Filtered Iterator |
Applies conditions to element selection |
Data filtering |
Advanced Iteration Techniques
Generator-Based Iterators
def custom_range_generator(start, end, step=1):
current = start
while current < end:
yield current
current += step
## Using the generator
for value in custom_range_generator(0, 10, 2):
print(value)
Iterator Composition
class ChainedIterator:
def __init__(self, *iterables):
self.iterables = iterables
self.current_iterable_index = 0
self.current_iterator = iter(self.iterables[0])
def __iter__(self):
return self
def __next__(self):
try:
return next(self.current_iterator)
except StopIteration:
self.current_iterable_index += 1
if self.current_iterable_index < len(self.iterables):
self.current_iterator = iter(self.iterables[self.current_iterable_index])
return next(self.current_iterator)
raise StopIteration
Iterator Flow Visualization
graph TD
A[Start Custom Iterator] --> B{Initialization}
B --> C[Define __iter__ Method]
C --> D[Implement __next__ Method]
D --> E{Has More Elements?}
E -->|Yes| F[Return Current Element]
F --> G[Update Iterator State]
G --> E
E -->|No| H[Raise StopIteration]
Iterator vs List Comprehension
## Memory-efficient iterator
def large_data_iterator(limit):
for i in range(limit):
yield i * i
## Memory-intensive list comprehension
def large_data_list(limit):
return [i * i for i in range(limit)]
LabEx Practical Insights
At LabEx, we emphasize that custom iterator design is crucial for:
- Memory optimization
- Lazy evaluation
- Creating flexible data processing pipelines
Key Design Principles
- Implement
__iter__()
and __next__()
methods
- Manage internal state carefully
- Handle iteration termination with
StopIteration
- Consider memory efficiency
- Use generators for simpler implementations