[Python-ideas] Change how Generator Expressions handle StopIteration
Guido van Rossum
guido at python.org
Sat Nov 1 17:50:05 CET 2014
I think you're on to something. But I think both your examples have a
problem, even though your second one "works".
If we weren't forced by backward compatibility I would have made it much
harder for StopIteration to "leak out". Currently a generator can either
return or raise StopIteration to signal it is done, but I think it would
have been better if StopIteration was treated as some kind of error in this
case. Basically I think any time a StopIteration isn't caught by a for-loop
or an explicit try/except StopIteraton, I feel there is a bug in the
program, or at least it is hard to debug.
I'm afraid that ship has sailed, though...
On Sat, Nov 1, 2014 at 7:56 AM, yotam vaknin <tomirendo at gmail.com> wrote:
> Hi,
>
> I would like to purpose that generator expressions will not catch
> StopIteration exception, if this exception did not come from the iterated
> object's __next__ function specifically. So generator expressions will be
> able to raise StopIteration by calculating the current value of the
> Generator.
>
> Here is an example of a use-case :
>
> def izip(*args):
> iters = [iter(obj) for obj in args]
> while True:
> yield tuple(next(it) for it in iters)
>
> a = izip([1,2],[3,4])
> print(next(a),next(a),next(a)) #Currently prints : (1, 3) (2, 4) ()
> list(izip([1,2],[3,4])) #Currently never returns
>
> Even thought this is the PEP described behaviour, I think this is an
> unwanted behaviour.
>
> I think Generator Expressions should work like List Comprehension in that
> sense:
>
> def iizip(*args):
> iters = [iter(obj) for obj in args]
> while True:
> yield tuple([next(it) for it in iters])
>
> tuple(iizip([1,2],[3,4])) #Returns [(1, 3), (2, 4)]
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141101/25f567d9/attachment.html>
More information about the Python-ideas
mailing list