Screwing Up looping in Generator
python at deborahswanson.net
Tue Jan 3 00:12:22 EST 2017
Erik wrote, on January 03, 2017 3:53 PM
> On 03/01/17 23:05, Deborah Swanson wrote:
> > 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.
> Out of interest, *why* was it deemed necessary to do
> something different
> if you don't know how many items the generator will generate? Was any
> rationale given for that?
> for x in foo:
> ... where foo is any iterable (something that has a __iter__ method
> defined - including generators) will just bind each value in
> turn to 'x'
> and will exit when the StopIteration exception is raised under the
> covers by the iterator that is iterating over the iterable.
> Some generators are infinite (and their iterator will never raise a
> StopIteration exception).
The main reason you might want to catch the StopIteration exception is to do
something else before your code simply stops running. If all you're doing is
run a generator til it's out of gas, and that's all you want it to do, then
there's no need to catch anything. There's lots of situations where this is
exactly what you want. It might even be the most frequent use of generators,
though I wouldn't know.
More information about the Python-list