[Python-ideas] Change how Generator Expressions handle StopIteration

Ron Adam ron3200 at gmail.com
Tue Nov 11 17:38:24 CET 2014



On 11/11/2014 06:21 AM, Nick Coghlan wrote:
>
> Option 2 would be to assume the new exception is something generic like
> RuntimeError, requiring the inner loop to be converted to statement form:
>
>
>      def izip(*args):
>          iters = [iter(obj) for obj in args]
>          while True:


>              entry = []
>              for it in iters:
>                  try:
>                      item = next(it)
>                  except StopIteration:
>                      return # One of the iterators has been exhausted
>                  entry.append(item)
>              yield tuple(entry)

When I was experimenting with this earlier, I needed the try-except to 
catch the StopIteration exception in order to do a "break".  Which gave me 
the current behaviour of the generator expression being discussed.

Replacing break with return, as above, gave the expected behaviour, but 
also just removing the try-except and letting the StopIteration propagate 
out, worked as well.  That is, StopIteration(None) is equivalent to "return 
None" in the context above.

Can you point me to the source file that implements generator expression 
byte code or C code?  I wanted to look at that to see what was actually 
going on, but it looks like it may be a combination of a regular generator 
with a condition at some point to handle it slightly different.

Cheers,
    Ron














More information about the Python-ideas mailing list