Generators and iterators

Geert-Jan Van Den Bogaerde gvdbogae at vub.ac.be
Tue Mar 5 10:15:34 EST 2002


On 5 Mar 2002, Bertrand Geston wrote:

> Hello,
> 
> I just quickly red the page about new features in Python 2.2 and tried - for
> fun - to test it. It must be obvious but I really don't see why, in the
> console transcript below, z.next() send back None and not 1,2 and 3
> whereas it does it correctly 3 times, no more no less.
> 
> TIA.
> 
> B.
> 
> Sorry for the methods and class names. Here is it:
> 
> PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32.
> Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see
> 'Help/About PythonWin' for further copyright information.
> >>> from __future__ import generators
> >>> def t():
> ...  yield 1
> ...  yield 2
> ...  yield 3
> ...
> >>> tt = t()
> >>> tt
> <generator object at 0x010958F8>
> >>> tt.next()
> 1
> >>> tt.next()
> 2
> >>> tt.next()
> 3
> >>> tt.next()
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> StopIteration
> >>> class Z:
> ...  def __init__(self):
> ...   self.ttt=t()
> ...  def __iter__(self):
> ...   return self
> ...  def next(self):
> ...   self.ttt.next()

You probably want

return self.ttt.next()

here instead of just self.ttt.next()

Geert-Jan

> ...
> >>> z=Z()
> >>> for i in z:
> ...  print i
> ...
> None
> None
> None
> >>> z=Z()
> >>> z.next()
> >>> z.next()
> >>> z.next()
> >>> z.next()
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 7, in next
> StopIteration
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 






More information about the Python-list mailing list