Screwing Up looping in Generator

Deborah Swanson python at deborahswanson.net
Mon Jan 2 22:21:10 EST 2017



-----Original Message-----
From: Matt Wheeler [mailto:m at funkyhat.org]
Sent: Tuesday, January 03, 2017 1:47 PM To: python at deborahswanson.net; Sayth 
Renshaw; python-list at python.org
Subject: Re: Screwing Up looping in Generator


On Tue, 3 Jan 2017 at 20:17 Deborah Swanson <python at deborahswanson.net> wrote:

> What's the code for your generator? And I don't see where you
> call 'next'.

I think you're expecting

        for file in rootobs

to get the next yield for you from rootobs, but unless someone corrects me, I 
don't think you can expect a 'for' statement to do that. You need to have a 
'next' statement inside your for loop to get the next yield from the generator.




Yes, you absolutely can expect a for statement to do that. It will accept any 
iterable as its `y`.

>> And here is someone correcting me, which I sort of suspected there
might be. Yes,
>> range is an iterator, but I didn't know a generator could also be
used as an iterator.
>> Makes perfect sense though, a generator does dispense its yields in
the sequence
>> defined by the generator.


`for x in y: stuff(x)` is effectively syntactic sugar for:


iterator = iter(y)
while True:
    try:
        x = next(iterator)
    except(StopIteration):
        break
    stuff(x)

Manually calling `next()` inside a `while True:` is quite an unusual thing to 
do.

>> And you don't need to do it very often. The only use case I know is
this one, where the number of yields the generator can output is unknown (here, 
the number of files the generator can access is unknown). You might recall that 
the original poster wanted to use a while, but didn't know how to terminate it. 
At least that's how I interpreted what he was saying.


range() is not part of the for syntax at all, it's completely separate, it 
simply returns an iterator which the for loop can use, like any other.
--

>> I see that now, I just didn't know a generator could be used as an
iterator.

--
Matt Wheeler
http://funkyh.at




More information about the Python-list mailing list