I've been looking for a good way to write a Python iterator that is based on a generator. I've found many tutorials on the topic of iterators and many on generators and the yield statement, but nothing that combines the two. I've built a small example that works and wondered if there is a better way to do this.
class myIterator :
def __init__(self, n) :
self.last = n
self.myGen = self.myGenerator()
def __iter__(self) :
return self.myGenerator()
def next(self) :
return self.myGen.next()
def myGenerator(self) :
prev = 0
fib = 1
while fib < self.last :
res = fib
yield res
fib = fib + prev
prev = res
raise StopIteration
I've used this technique in a real world program that can be found at SQLStatements.py in my Github repository
The most perplexing part of this was defining the next() function. The obvious solutions all returned the first element every time they were called. Storing an instance variable containing the generator works, but seems to be a kludge.
If you know a better way to do this or a good tutorial that covers this topic please let me know.
Edit: The third example posted by @MartijnPieters solves the problem completely. Saving the self.generator.next function in self.next provides a next function. I hope this helps someone else trying to solve this problem.
__iter__
returnself.myGen
? – krlmlr Jan 6 '13 at 22:03