Iterators vs. Generators
Chris Liechti
cliechti at gmx.net
Mon Jun 10 19:40:35 EDT 2002
aahz at pythoncraft.com (Aahz) wrote in news:ae3a6f$9d9$1 at panix1.panix.com:
> So when would one actually write an iterator instead of a generator?
> I've been trying to think of an example and failing.
don't know, maybe when you don't like the additional loop in the generator
(see example below)
maybe the iterator has advantages when the data in the object changes or
has to be chaged as the object q (from below) _is_ the iteraror but it's
_not_ the generator (but this does not matter in the example below ...).
if you pass "i = iter(q)" somewhere then with the iterator (and forget
about q) you can still modify the original object as "i is q" (at least in
my example), but this is not even possible with a generator.
iterators can be generated implicit by __iter__ in a "for", but a generator
needs a factory function (of course that can be named __iter__ ...)
seems to be a matter of taste...
chris
PS: why is Queue not iterable by default?
here's a Queue for fun <wink>:
----
#!/usr/bin/env python
from __future__ import generators
import Queue, threading, time
class Q(Queue.Queue):
def __iter__(self):
return self
def next(self):
x = self.get(1)
if x is None: raise StopIteration
return x
class Q2(Queue.Queue):
def __iter__(self):
while 1:
x = self.get(1)
if x is None: return
yield x
class Producer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.q = queue
def run(self):
for n in range(10):
time.sleep(0.2)
self.q.put(n)
self.q.put(None)
if __name__ == '__main__':
#iterator
q = Q()
print ":", q is iter(q), type(iter(q))
Producer(q).start()
for x in q:
print x
#generator
q = Q2()
print ":", q is iter(q), type(iter(q))
Producer(q).start()
for x in q:
print x
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list