generator object, next method

Terry Reedy tjreedy at udel.edu
Thu Sep 8 20:05:13 CEST 2005


"Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message 
news:7xll282cz4.fsf at ruckus.brouhaha.com...
> Duncan Booth <duncan.booth at invalid.invalid> writes:
>> 1) Every time you access gen.next you create a new method-wrapper 
>> object.
>
> Why is that?  I thought gen.next is a callable and gen.next() actually
> advances the iterator.  Why shouldn't gen.next always be the same object?

If you explicitly or implicitly (via for loop) calculate gen.next exact 
once (as I presume for loops do, and as I would for explicit while loop), 
then it is.  When you keep a reference to the wrapper, and call it 
repeatedly via that wrapper, then all is as you expect.

next_x = genfunc(*args).next
while True:
   x = next_x() # same next_x each time
   <do something with x>

Terry J. Reedy






More information about the Python-list mailing list