[Python-Dev] PEP 479: Change StopIteration handling inside generators (original) (raw)
Guido van Rossum guido at python.org
Fri Nov 21 19:44:28 CET 2014
- Previous message: [Python-Dev] PEP 479: Change StopIteration handling inside generators
- Next message: [Python-Dev] PEP 479: Change StopIteration handling inside generators
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Fri, Nov 21, 2014 at 9:18 AM, Steven D'Aprano <steve at pearwood.info> wrote:
I fear that there is one specific corner case that will be impossible to deal with in a backwards-compatible way supporting both Python 2 and 3 in one code base: the use of
return value
in a generator.In Python 2.x through 3.1,
return value
is a syntax error inside generators. Currently, the only way to handle this case in 2+3 code is by usingraise StopIteration(value)
but if that changes in 3.6 or 3.7 then there will be no (obvious?) way to deal with this case.
Note that using StopIteration for this purpose is a recent invention (I believe I invented it for the Google App Engine NDB library).
Before Python 3.3 this had to be essentially a private protocol implemented by the framework, and typically the framework defines a custom exception for this purpose -- either an alias for StopIteration, or a subclass of it, or a separate exception altogether. I did a little survey:
ndb uses "return Return(v)" where Return is an alias for StopIteration.
monocle uses "yield Return(v)", so it doesn't even use an exception.
In Twisted you write "returnValue(v)" -- IMO even more primitive since it's not even a control flow statement.
In Tornado you write "raise tornado.gen.Return(v)", where Return does not inherit from StopIteration. In Python 3.3 and later you can also write "return v", and the framework treats Return and StopIteration the same -- but there is no mention of "raise StopIteration(v)" in the docs and given that they have Return there should be no need for it, ever.
In Trollius (the backport of asyncio) you write "raise Return(v)", where Return is currently a subclass of StopIteration -- but it doesn't really have to be, it could be a different exception (like in Tornado).
So I haven't found any framework that recommends "raise StopIteration(v)". Sure, some frameworks will have to be changed, but they have until Python 3.6 or 3.6, and the changes can be made to work all the way back to Python 2.7.
-- --Guido van Rossum (python.org/~guido) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20141121/16ed8965/attachment-0001.html>
- Previous message: [Python-Dev] PEP 479: Change StopIteration handling inside generators
- Next message: [Python-Dev] PEP 479: Change StopIteration handling inside generators
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]