Screwing Up looping in Generator
Deborah Swanson
python at deborahswanson.net
Mon Jan 2 22:05:20 EST 2017
Chris Angelico wrote, on January 03, 2017 2:31 PM
>
> On Wed, Jan 4, 2017 at 8:19 AM, Deborah Swanson
> <python at deborahswanson.net> wrote:
> > while True:
> > try:
> > file = files.next()
> > except StopIteration:
> > break
>
> Small side point: Try to avoid calling a generator object's
> .next() method directly. Normally, when you _do_ want to do
> this, you should be calling next(files). In Python 3, the
> magic method is now __next__(), which emphasizes that it's
> for defining, not calling.
>
> As others have pointed out, though, the for loop is the
> correct tool for this job.
>
> ChrisA
Ok, I learned how to use generators in Python 2.7.8, which may be different
from Python 3 for generators. But I learned from MIT's online introduction to
python course, and they certainly seem to know python well. So what is the
correct way to call the generator's next yield in Python 3? We only learned to
use the next function. If you don't use the next function, what do you use?
And yes, we usually used for loops for generators, unless you don't know when
the generator will be exhausted. As in this case, where the number of files the
generator can provide is unknown. Then we used the while True, break on
StopIteration method.
More information about the Python-list
mailing list