classification
Title: Implemenation of the PEP 492 - Coroutines with async and await syntax
Type: enhancement Stage: resolved
Components: Interpreter Core Versions: Python 3.5
process
Status: closed Resolution: fixed
Dependencies: 2292 22906 24018 24180 24184 24315 24316 24400 Superseder:
Assigned To: yselivanov Nosy List: alex.gronholm, asvetlov, gvanrossum, haypo, ncoghlan, python-dev, scoder, yselivanov
Priority: release blocker Keywords: patch

Created on 2015-04-20 19:33 by haypo, last changed 2015-06-20 19:39 by yselivanov. This issue is now closed.

Files
File name Uploaded Description Edit
await_01.patch yselivanov, 2015-04-20 19:55 review
await_02.patch yselivanov, 2015-04-21 03:59 review
await_03.patch yselivanov, 2015-05-07 20:13 review
await_04.patch yselivanov, 2015-05-08 21:15 review
await_05.patch yselivanov, 2015-05-11 01:32 review
await_06.patch yselivanov, 2015-05-11 19:59 review
with.patch yselivanov, 2015-05-13 03:36 review
Messages (69)
msg241678 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-04-20 19:45
Here's the first patch (git diff master..await). Should be easier to review and work from there.
msg241679 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-04-20 19:55
Attaching a patch generated with mercurial
msg241687 - (view) Author: STINNER Victor (haypo) * (Python committer) Date: 2015-04-20 21:43
Does the implementation depends on the implementation of the PEP 479? (issue #22906)

> Attaching a patch generated with mercurial

Next time, if possible, try to skip generated files. Maybe write a script for that, but sorry I don't know how :-(
msg241697 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-04-21 03:59
Attaching a revised patch (all Victor's comments but asyncio changes)
msg242056 - (view) Author: Stefan Behnel (scoder) * Date: 2015-04-26 15:11
Could we have type slots for the new special methods? Otherwise, implementing the protocol in C would be fairly inefficient, especially for async iteration.

I'm asking because Cython's generator type is not Python's generator type, but implementing the rest of the proposed protocol doesn't seem to be all that difficult.
msg242064 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-04-26 17:27
> Could we have type slots for the new special methods? Otherwise, implementing the protocol in C would be fairly inefficient, especially for async iteration.

I don't think it's necessary to have slots for __aiter__, __anext__, __aenter__ and __aexit__.  Async iteration will never be as fast as regular iteration, and there is plenty overhead in it.  And we don't need slots for async context managers as we don't have slots for regular ones.

What might be a good idea is to add a slot for __await__ method -- tp_await.  This will allow to implement Futures in C efficiently.  I'd rename 'tp_reserved' for this purpose.

Victor, your thoughts?
msg242086 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-04-26 23:27
In fact I will likely add tp_await in the next PEP iteration. I need it to implement another feature.
msg242304 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-01 12:19
> I don't think it's necessary to have slots for __aiter__, __anext__, __aenter__ and __aexit__.  Async iteration will never be as fast as regular iteration, and there is plenty overhead in it.

You seem to be assuming that the outer loop is the asyncio I/O loop. That might not be the case. It might be a thread-pool executor, it might be an in-memory task switcher, or it might just be something passing on items from a list. At least "__anext__" is worth being fast, IMHO.

Also note that one advantage of slots is that the user can cache their value to keep calling the same C function multiple times. That is not the case for a Python method, which can easily be replaced. Some iterators do that with their __next__ method, and it's perfectly valid. Having to look up the Python method on each iteration and calling through it sounds like unnecessary overhead.
msg242326 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2015-05-01 15:18
I think we can continue this discussion *after* the PEP's been accepted.
msg242627 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-06 00:16
I'll upload the most recent patch soon.
msg242731 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-07 20:13
Third patch attached.  Victor, it would be great if you can review it!
msg242779 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-08 21:15
Another iteration:
- support of new syntax in lib2to3
- collections.abc.Awaitable
msg242793 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-09 03:29
We also need a Coroutine ABC. Both the "GeneratorType" and "CO_COROUTINE" checks are too restrictive. Also see issue 24018, which this one should in fact depend on.
msg242848 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-10 03:34
Review sent - very nice work on this Yury.

Highlights:

* I concur with Stefan that we should have a full PyCoroutineMethods struct at the C level, with a "tp_as_coroutine" pointer to that replacing the current tp_reserved slot

* I also concur with Stefan about adding a Coroutine ABC

* PyType_FromSpec (and typeslots.h) will need updating once we agree on a slot structure (with my recommendation being "define C level slots for all of the new PEP 492 methods")

* I found CO_COROUTINE/CO_NATIVE_COROUTINE confusing as a reader of the implementation, as they only told me how the objects were defined, rather than telling me why I should care. Based on what I gleaned of their intended purpose from reading the implementation, I suggest switching this to instead use CO_COROUTINE (set for all coroutines, regardless of how they were defined) and CO_ITERABLE_COROUTINE (set only for those coroutines that also support iteration), and adjusting the naming of other APIs accordingly.

* I found the names of the WITH_CLEANUP_ENTER and WITH_CLEANUP_EXIT bytecodes misleading, as they don't refer to the corresponding context management phases - they're both related to the "exit" phase. WITH_CLEANUP_START and WITH_CLEANUP_FINISH should be clearer for readers (both of the implementation and of the disassembled bytecode).
msg242860 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-10 16:21
> Review sent - very nice work on this Yury.

Thanks a lot, Nick!

Highlights:

> * I concur with Stefan that we should have a full PyCoroutineMethods struct at the C level, with a "tp_as_coroutine" pointer to that replacing the current tp_reserved slot

Do you think that tp_as_async is a better name?  (I explained my point of view in code review comments)

Also, do we need slots for __aenter__ and __aexit__? We don't have slots for regular context manager protocol, fwiw.

> * I also concur with Stefan about adding a Coroutine ABC

I will.  We definitely need it.

> * PyType_FromSpec (and typeslots.h) will need updating once we agree on a slot structure (with my recommendation being "define C level slots for all of the new PEP 492 methods")

> * I found CO_COROUTINE/CO_NATIVE_COROUTINE confusing as a reader of the implementation, as they only told me how the objects were defined, rather than telling me why I should care. Based on what I gleaned of their intended purpose from reading the implementation, I suggest switching this to instead use CO_COROUTINE (set for all coroutines, regardless of how they were defined) and CO_ITERABLE_COROUTINE (set only for those coroutines that also support iteration), and adjusting the naming of other APIs accordingly.

I agree that CO_COROUTINE is something that we should use for 'async def' functions (instead of CO_NATIVE_COROUTINE).  However, CO_ITERABLE_COROUTINE sounds a bit odd to me, as generator-based coroutines (at least in asyncio) aren't supposed to be iterated over.  How about CO_GENBASED_COROUTINE flag?


> * I found the names of the WITH_CLEANUP_ENTER and WITH_CLEANUP_EXIT bytecodes misleading, as they don't refer to the corresponding context management phases - they're both related to the "exit" phase. WITH_CLEANUP_START and WITH_CLEANUP_FINISH should be clearer for readers (both of the implementation and of the disassembled bytecode).

Big +1. Your names are much better.
msg242862 - (view) Author: Andrew Svetlov (asvetlov) * (Python committer) Date: 2015-05-10 17:40
On Sun, May 10, 2015 at 7:21 PM, Yury Selivanov <report@bugs.python.org> wrote:
>
> Yury Selivanov added the comment:
>
>> Review sent - very nice work on this Yury.
>
> Thanks a lot, Nick!
>
> Highlights:
>
>> * I concur with Stefan that we should have a full PyCoroutineMethods struct at the C level, with a "tp_as_coroutine" pointer to that replacing the current tp_reserved slot
>
> Do you think that tp_as_async is a better name?  (I explained my point of view in code review comments)
>
> Also, do we need slots for __aenter__ and __aexit__? We don't have slots for regular context manager protocol, fwiw.
>
>> * I also concur with Stefan about adding a Coroutine ABC
>
> I will.  We definitely need it.
>
>> * PyType_FromSpec (and typeslots.h) will need updating once we agree on a slot structure (with my recommendation being "define C level slots for all of the new PEP 492 methods")
>
>> * I found CO_COROUTINE/CO_NATIVE_COROUTINE confusing as a reader of the implementation, as they only told me how the objects were defined, rather than telling me why I should care. Based on what I gleaned of their intended purpose from reading the implementation, I suggest switching this to instead use CO_COROUTINE (set for all coroutines, regardless of how they were defined) and CO_ITERABLE_COROUTINE (set only for those coroutines that also support iteration), and adjusting the naming of other APIs accordingly.
>
> I agree that CO_COROUTINE is something that we should use for 'async def' functions (instead of CO_NATIVE_COROUTINE).  However, CO_ITERABLE_COROUTINE sounds a bit odd to me, as generator-based coroutines (at least in asyncio) aren't supposed to be iterated over.  How about CO_GENBASED_COROUTINE flag?
>

Maybe CO_ASYNC_COROUTINE and CO_OLDSTYLE_COROUTINE?
This is wild proposal, feel free to ignore it.

>
>> * I found the names of the WITH_CLEANUP_ENTER and WITH_CLEANUP_EXIT bytecodes misleading, as they don't refer to the corresponding context management phases - they're both related to the "exit" phase. WITH_CLEANUP_START and WITH_CLEANUP_FINISH should be clearer for readers (both of the implementation and of the disassembled bytecode).
>
> Big +1. Your names are much better.
>
> ----------
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <http://bugs.python.org/issue24017>
> _______________________________________
msg242877 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-11 01:32
New patch is attached.

Nick, I think that all of your feedback should be addressed in this patch.

Major changes:

1. There are two code flags now: CO_COROUTINE and CO_GENBASED_COROUTINE (I'm OK to use another name, see my older comments).  CO_COROUTINE is assigned to all 'async def' code objects.  CO_GENBASED_COROUTINE is assigned to generator-based coroutines decorated with types.coroutine().

2. tp_await renamed to tp_as_async. (I'm OK to use another name, please see my older comment first) PyAsyncMethods struct holds three slots: am_await, am_aiter, am_anext.  Implementing am_exit would be tricky, because of how SETUP_WITH opcode is engineered.  I'd really prefer to not to add it.

3. collections.abc.Coroutine.

4. etc (all other feedback from you).
msg242912 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-11 19:59
Nick, Guido, 
Updated patch attached.
msg242927 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-12 00:03
Latest version looks good to me (aside from a quibble about whether StopAsyncIteration should inherit from BaseException instead of Exception - see my review for details).

Based on Guido's explanation in the review, I also suggested adding the following example method to the PEP as part of the rationale for StopAsyncIteration:

    def __anext__(self):
        try:
            data = await self._get_data()
        except EOFError:
            raise StopAsyncIteration
        return data

The trick is that when __anext__ is itself a coroutine, we really do have 3 exit paths:

* suspension to wait for events (await)
* returning the next value (return)
* terminating iteration (raise StopAsyncIteration)
msg242928 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-12 00:16
Guido convinced me that having StopAsyncIteration inherit from Exception was the right approach, as it means errors are more likely to be of the "we caught it when we shouldn't have" variety, rather than the harder to debug "an exception escaped when it shouldn't have" variety. This isn't like SystemExit, KeyboardInterrupt or GeneratorExit where they're specifically designed to reliably terminate a thread of execution.

That means I can offer an unreserved +1 on the current patch (#6) for beta 1 :)
msg242931 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-12 02:31
New changeset 957478e95b26 by Yury Selivanov in branch '3.4':
asyncio: Support PEP 492. Issue #24017.
https://hg.python.org/cpython/rev/957478e95b26

New changeset 44c1db190525 by Yury Selivanov in branch 'default':
asyncio: Merge 3.4 -- Support PEP 492. Issue #24017.
https://hg.python.org/cpython/rev/44c1db190525
msg242935 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-12 03:03
New changeset eeeb666a5365 by Yury Selivanov in branch 'default':
PEP 0492 -- Coroutines with async and await syntax. Issue #24017.
https://hg.python.org/cpython/rev/eeeb666a5365
msg242936 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-12 03:06
Guido, Nick, Victor,
Thanks for your reviews and guidance!  The patch has been committed to the default branch.
msg242937 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2015-05-12 03:23
Thank you Yury! You are a coding machine.

On Mon, May 11, 2015 at 8:06 PM, Yury Selivanov <report@bugs.python.org>
wrote:

>
> Yury Selivanov added the comment:
>
> Guido, Nick, Victor,
> Thanks for your reviews and guidance!  The patch has been committed to the
> default branch.
>
> ----------
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <http://bugs.python.org/issue24017>
> _______________________________________
>
msg242938 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-12 04:06
New changeset 3a3cc2b9a1b2 by Yury Selivanov in branch 'default':
Issue 24017: Update NEWS file.
https://hg.python.org/cpython/rev/3a3cc2b9a1b2
msg242979 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-12 15:30
New changeset 0dc3b61f1dfa by Yury Selivanov in branch 'default':
Issue #24017: Plug ref leak.
https://hg.python.org/cpython/rev/0dc3b61f1dfa
msg242982 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-12 15:46
New changeset ee7d2c9c70ab by Yury Selivanov in branch '3.4':
asyncio: Make sure sys.set_coroutine_wrapper is called *only* when loop is running.
https://hg.python.org/cpython/rev/ee7d2c9c70ab

New changeset 874edaa34b54 by Yury Selivanov in branch 'default':
asyncio: Make sure sys.set_coroutine_wrapper is called *only* when loop is running.
https://hg.python.org/cpython/rev/874edaa34b54
msg242984 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-12 18:28
New changeset 9d2c4d887c19 by Yury Selivanov in branch 'default':
Issue #24017: Unset asyncio event loop after test.
https://hg.python.org/cpython/rev/9d2c4d887c19
msg243031 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-13 03:36
Nick, Guido,

Attached is a patch that fixes a refleak in 'async with' implementation.

The problem is related to WITH_CLEANUP_START/WITH_CLEANUP_FINISH opcodes.

For regular 'with' statements, these opcodes go one after another (essentially, it was one opcode before 'async with').

For 'async with' statements, we have a GET_AWAITABLE/YIELD_FROM pair between them.

Now, if an error occurred during running a GET_AWAITABLE or a YIELD_FROM opcode, WITH_CLEANUP_FINISH was unreachable.  All blocks were correctly unwound by the eval loop, but exception object got too many DECREFS.

My solution is to continue using WITH_CLEANUP_START/WITH_CLEANUP_FINISH opcodes, but use SETUP_EXCEPT to guard them and nested YIELD_FROM and GET_AWAITABLE.

In case of an exception, I propose to use another new opcode -- ASYNC_WITH_CLEANUP_EXCEPT.  It unwinds the block set up by SETUP_EXCEPT, restores exception, NULLifies a copy of exception in the stack and does 'goto error', letting eval loop do the rest.

"./python.exe -m test -R3:3 test_coroutines" with this patch reports no refleaks.  I also updates test_coroutines with a lot of new 'async with' tests, I think that I got all usecases covered.

Please take a look at the patch, I want to commit it as soon as possible.
msg243033 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-13 05:00
I'm bothered by the remarkable proliferation of new opcodes for the PEP 492 handling. Is there are a specific reason this implicit exception handler can't be decomposed and implemented using the same opcodes as are used to implement explicit exception handlers?
msg243035 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-13 05:10
> Is there are a specific reason this implicit exception handler can't be decomposed and implemented using the same opcodes as are used to implement explicit exception handlers?

I don't think it's possible to replace ASYNC_WITH_CLEANUP_EXCEPT opcode with some combination of existing opcodes.

What might be possible is to implement 'async with' without using WITH_CLEANUP_* opcodes at all.  Let me try that.
msg243036 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-13 05:15
I'm going to dig into this one locally, as it sounds to me like something may be going wrong with the refcounts in the complex stack manipulation involved in WITH_CLEANUP. It seems plausible that there's a genuinely missing incref/decref pair somewhere in the non-exceptional path, which the proposed new opcode is working around.
msg243037 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-13 05:19
Avoiding WITH_CLEANUP entirely in the async case also sounds like a plausible approach. Either way, I'm also on IRC now if you want to thrash this out there.
msg243038 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-13 05:19
I'd suggest you to look at ceval.c before PEP 492 patch then (where there is just one WITH_CLEANUP opcode).
msg243041 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-13 05:54
New changeset e39fd5a8501a by Nick Coghlan in branch 'default':
Issue 24017: fix for "async with" refcounting
https://hg.python.org/cpython/rev/e39fd5a8501a
msg243042 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-13 06:06
A bit more detail on the patch-as-merged: it has all of Yury's new tests, but the actual bug turned out to just be a missing INCREF/DECREF pair in WITH_CLEANUP_START and WITH_CLEANUP_FINISH.

In the success case the reference counting errors cancelled each other out without causing a problem, as there was always a second live reference to the exception object on the stack.

However, in the case where the awaitable threw an exception the standard exception handling machinery took care of removing the saved exception from the stack, and correctly decremented the reference count, which then caused problems due to the missing INCREF in WITH_CLEANUP_START.
msg243117 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-13 19:46
Closing the issue.  I'll open a new one for missing documentation.  Thanks!
msg243118 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2015-05-13 19:49
BTW, a shout out to Nick for doing most of the review for this monster patch. Thanks!
msg243119 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-13 20:49
New changeset 0d80d46adfdb by Yury Selivanov in branch 'default':
Issue 24017: More tests for 'async for' and 'async with'.
https://hg.python.org/cpython/rev/0d80d46adfdb
msg243759 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-21 16:03
New changeset ff983ee10b3e by Yury Selivanov in branch 'default':
Issue 24017: Use abc.Coroutine in inspect.iscoroutine() function
https://hg.python.org/cpython/rev/ff983ee10b3e
msg244175 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-27 15:10
New changeset 843fe7e831a8 by Yury Selivanov in branch '3.5':
Issue 24297: Update symbol.py. See also issue 24017.
https://hg.python.org/cpython/rev/843fe7e831a8

New changeset 87509d71653b by Yury Selivanov in branch 'default':
Issue 24297: Update symbol.py. See also issue 24017.
https://hg.python.org/cpython/rev/87509d71653b
msg244252 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 03:30
I added a couple of review comments to patch 6, but since no-one has responded so far, I guess they simply haven't been noticed. So I'll just repeat them here.

1)
getawaitablefunc / aiternextfunc / getaiterfunc

Is there a reason why these need to have their specific C type name instead of just reusing unaryfunc, or at least the existing iternextfunc / getiterfunc? They are unprefixed global names in the C namespace and I think we should be careful when adding more of those.

2)
Awaitable.register(Coroutine)

I think this is incorrect. A Coroutine is not Awaitable unless it also implements "__await__". How else should it be awaited?

3)
I propose to use this wrapping code as a fallback for types.coroutine() in the case that a Generator (ABC) is passed instead of a generator (yield):

  class types_coroutine(object):
    def __init__(self, gen):
        self._gen = gen

    class as_coroutine(object):
        def __init__(self, gen):
            self._gen = gen
            self.send = gen.send
            self.throw = gen.throw
            self.close = gen.close

        def __await__(self):
            return self._gen

    def __call__(self, *args, **kwargs):
        return self.as_coroutine(self._gen(*args, **kwargs))

Note that the resulting Awaitable Coroutine type is not an Iterable. This differs from a (yield) coroutine, but it matches the Coroutine and Awaitable protocols, and the intention to separate both in order to avoid mistakes on user side.


Additionally, regarding the tests:
4)

    def test_func_2(self):
        async def foo():
            raise StopIteration

        with self.assertRaisesRegex(
                RuntimeError, "generator raised StopIteration"):

            run_async(foo())

Why is this actually necessary? I'm aware that it's also mentioned in the PEP, but is there an actual reason why a coroutine should behave the same as a generator here? Is it just an implementation detail for legacy reasons because generators and coroutines happen to share the same type implementation? (I don't think they need to, BTW.)

5)
    def test_func_8(self):
        @types.coroutine
        def bar():
            return (yield from foo())

        async def foo():
            return 'spam'

        self.assertEqual(run_async(bar()), ([], 'spam') )

I find it surprising that this works at all. Yield-from iterates, and a coroutine is not supposed to be iterable, only awaitable (at least, that's what all error messages tell me when I try it). So why should "yield from" work on them? What if foo() was not an Iterable but a Coroutine? Should "yield from" then call "__await__" on it internally? I would find that *really* surprising, but given the above, I think it would be necessary to achieve consistency.
msg244257 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-28 03:54
> 2) Awaitable.register(Coroutine)
> I think this is incorrect. A Coroutine is not Awaitable unless it also implements "__await__". How else should it be awaited?

It *is* correct, see PEP 492.  Awaitable is either a coroutine *or* an object with an __await__ method.  Generally, being an awaitable means that the object can be used in "await" expression.


> 3)
> I propose to use this wrapping code as a fallback for types.coroutine() in the case that a Generator (ABC) is passed instead of a generator (yield):

Just implement tp_await/__await__ for coroutine-like objects coming from C-API or Cython.  In general, iteration protocol is still the foundation for Future-like objects, so there is nothing wrong with this.

Generator ABC isn't supposed to be used with "await" expression.


> 4)
> 
>     def test_func_2(self):
>         async def foo():
>             raise StopIteration
> 
>         with self.assertRaisesRegex(
>                 RuntimeError, "generator raised StopIteration"):
> 
>             run_async(foo())

> Why is this actually necessary? I'm aware that it's also mentioned in the PEP, but is there an actual reason why a coroutine should behave the same as a generator here? Is it just an implementation detail for legacy reasons because generators and coroutines happen to share the same type implementation? (I don't think they need to, BTW.)

Coroutines are implemented on top of generators.  Until we clearly separate them (in 3.6?) I don't think we should allow coroutines to bubble up StopIteration.

> 5)
>     def test_func_8(self):
>         @types.coroutine
>         def bar():
>             return (yield from foo())
> 
>        async def foo():
>             return 'spam'
> 
>         self.assertEqual(run_async(bar()), ([], 'spam') )
> 
> I find it surprising that this works at all. Yield-from iterates, and a coroutine is not supposed to be iterable, only awaitable (at least, that's what all error messages tell me when I try it). So why should "yield from" work on them? What if foo() was not an Iterable but a Coroutine? Should "yield from" then call "__await__" on it internally? I would find that *really* surprising, but given the above, I think it would be necessary to achieve consistency.

This is a special backwards-compatibility thing.  In general, generators cannot yield-from coroutines (unless they are decorated with @types.coroutine).
msg244258 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 03:59
Another question: is it ok if Cython implements and uses the "tp_as_async" slot in all Py3.x versions (3.2+)? It shouldn't hurt, but it would speed up async/await in Cython at least under Py3.x. Only Py2.6/7 would then have to resort to calling "__await__()" etc. at the Python level.

One drawback is that Py<3.5 currently (needlessly) checks that "tp_reserved" and "tp_richcompare" are both implemented, but that can be worked around by also implementing the latter...
msg244261 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 04:18
> It *is* correct, see PEP 492.  Awaitable is either a coroutine *or* an object with an __await__ method.

"coroutine", yes. But "Coroutine"? Shouldn't the Coroutine ABC then require
"__await__" to be implemented? Maybe even by inheriting from Awaitable?

> Just implement tp_await/__await__ for coroutine-like objects coming from C-API or Cython.

Sure, that's how it's done. (Specifically, Coroutine is not an
Iterable/Iterator, but its __await__() returns a thin Iterator that simply
calls into the Generator code. A bit annoying and slowish, but that's what
it takes.)

I was just wondering how Cython should compile Python code that makes use
of this decorator. The Coroutine and Generator types are separated in
Cython now, and I think that's actually the right thing to do. This
types.coroutine() decorator and special casing in CPython's code base gets
a bit in the way here.

> In general, iteration protocol is still the foundation for Future-like objects

That's not really reflected in the ABCs, is it?
msg244264 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-28 04:35
> > It *is* correct, see PEP 492. Awaitable is either a coroutine *or* an object with an __await__ 
> method.
> 
> "coroutine", yes. But "Coroutine"? Shouldn't the Coroutine ABC then require
> "__await__" to be implemented? Maybe even by inheriting from Awaitable?

This is an interesting idea.

Practically, when you register something as a Coroutine, you expect it to
be compatible with ‘await’ expressions.  And that’s only possible if
__await__ is implemented.

I’m curious what Guido and Nick think about this.  I think that we can
derive Coroutine from Awaitable.


> > Just implement tp_await/__await__ for coroutine-like objects coming from C-API 
> or Cython.
> 
> Sure, that's how it's done. (Specifically, Coroutine is not an
> Iterable/Iterator, but its __await__() returns a thin Iterator that simply
> calls into the Generator code. A bit annoying and slowish, but that's what
> it takes.)

Can't your Coroutine object return itself from its __await__, and implement 
__next__?  Like genobject in CPython simply returns self from its __iter__.


> I was just wondering how Cython should compile Python code that makes use
> of this decorator. The Coroutine and Generator types are separated in
> Cython now, and I think that's actually the right thing to do. This
> types.coroutine() decorator and special casing in CPython's code base gets
> a bit in the way here.

I think we can update types.coroutine to continue using CO_ITERABLE_COROUTINE
for pure python generator functions.  And for something foreign we can use your
proposed design.  Would that be OK?

> 
> > In general, iteration protocol is still the foundation for Future-like objects
> 
> That's not really reflected in the ABCs, is it?

Awaitable has its __await__ defined as a generator...
msg244268 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-28 05:10
Thanks for highlighting these Stefan - you guessed correctly that I'd missed them on the review.

For your first question, I agree getawaitablefunc / aiternextfunc / getaiterfunc should all be dropped and replaced with the existing "unaryfunc".

For your second question, I agree it makes more sense for Coroutine to inherit from Awaitable than it does to have it registered with it.

For the other three, I don't have a strong opinion, except that we should make sure that whatever we do on the CPython side works by default for Cython.
msg244269 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-28 05:12
> For your first question, I agree getawaitablefunc / aiternextfunc / getaiterfunc should all be dropped and replaced with the existing "unaryfunc".


I have no problem with that.  But why do we have iternextfunc & getiterfunc (no "a" prefix)?
msg244273 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2015-05-28 05:35
Given that tp_call is just "ternaryfunc", my guess would be "because when the iterator protocol was added, someone went with function-pointer-type-per-slot rather than function-pointer-type-per-call-signature".

We *are* a little inconsistent here (e.g. "reprfunc" could also just use the "unaryfunc" signature), but Stefan's right that that isn't a good reason to *add* to the inconsistency.
msg244278 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 06:15
> Can't your Coroutine object return itself from its __await__, and implement 
> __next__?  Like genobject in CPython simply returns self from its __iter__.

That was my first try, sure, and it mostly worked. It has a drawback,
though: it's an incomplete implementation of the Iterator protocol. It's
still (mostly) an Iterator, but not an Iterable, so it depends on how you
use it whether you notice or not, and whether it works at all with other
code or not. There's a test for a failing "next(coro)" in your test suite,
for example, which would then not fail in Cython. OTOH, code cannot assume
that calling iter() or for-looping over on an Iterable is a sane thing to
do, because it doesn't work for Python's generator type based coroutine
either, so we might get away with it...

All of these little details make this trick appear like a potential source
of subtle inconsistencies or incompatibilities. But given that there will
almost certainly remain inconsistencies for compiled Python code, I'm not
sure yet which approach is better. It's not impossible that I'll end up
going back to the original design. I guess I'll eventually have to include
some benchmarks in the decision.

On a related note, my testing made me stumble over this code in
asyncio.tasks.Task():

        if coro.__class__ is types.GeneratorType:
            self._coro = coro
        else:
            self._coro = iter(coro)  # Use the iterator just in case.

This seems wrong regardless of how you look at it. And it definitely fails
with both designs.
msg244280 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 06:28
BTW, given that "iter(iterator)" works and returns the iterator, should we also allow "await x.__await__()" to work? I guess that would be tricky to achieve given that __await__() is only required to return any kind of arbitrary Iterator, and Iterators cannot be awaited due to deliberate restrictions. But it might be nice to have for wrapping purposes.
msg244281 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 06:48
>> Yield-from iterates, and a coroutine is not supposed to be iterable, only awaitable (at least, that's what all error messages tell me when I try it). So why should "yield from" work on them? What if foo() was not an Iterable but a Coroutine? Should "yield from" then call "__await__" on it internally? I would find that *really* surprising, but given the above, I think it would be necessary to achieve consistency.
> 
> This is a special backwards-compatibility thing.

That only answers the half-serious first part of my question. ;)

This code only works if foo() returns an Iterable, including a (yield)
coroutine:

    @types.coroutine
    def bar():
        return (yield from foo())

It does not work for arbitrary Coroutines as they are not iterable, but it
might trick people into writing code that fails for non-coroutine
Coroutines. I'd rather like to have this either work for any Coroutine or
not at all.
msg244303 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-28 14:53
New changeset 09327f653ec5 by Yury Selivanov in branch '3.4':
asyncio: Drop some useless code from tasks.py.
https://hg.python.org/cpython/rev/09327f653ec5

New changeset adf72cffceb7 by Yury Selivanov in branch '3.5':
asyncio: Drop some useless code from tasks.py.
https://hg.python.org/cpython/rev/adf72cffceb7

New changeset 9c0a00247021 by Yury Selivanov in branch 'default':
asyncio: Drop some useless code from tasks.py.
https://hg.python.org/cpython/rev/9c0a00247021
msg244307 - (view) Author: Roundup Robot (python-dev) Date: 2015-05-28 15:22
New changeset dfa0288c91fd by Yury Selivanov in branch '3.5':
Issue 24017: Drop getawaitablefunc and friends in favor of unaryfunc.
https://hg.python.org/cpython/rev/dfa0288c91fd

New changeset 99dcca3466d3 by Yury Selivanov in branch 'default':
Issue 24017: Drop getawaitablefunc and friends in favor of unaryfunc.
https://hg.python.org/cpython/rev/99dcca3466d3
msg244319 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-28 16:42
Stefan,


I've already committed fixes for:

1. getawaitablefunc / aiternextfunc / getaiterfunc -> unaryfunc
2. strange code in tasks.py doing "coro = iter(coro)" is now removed


I've also opened a couple of new issues (with patches for a review):

1. abc.Coroutine derived from abc.Awaitable: issue 24315
2. types.coroutine() to support Cython objects: issue 24316


I'll reply to some of your messages below:

> Another question: is it ok if Cython implements and uses the "tp_as_async" slot in all Py3.x versions (3.2+)? It shouldn't hurt, [..]

I think it's totally OK, given that you can workaround the drawback you mentioned.


>> Can't your Coroutine object return itself from its __await__, and implement 
>> __next__?  Like genobject in CPython simply returns self from its __iter__.

> That was my first try, sure, and it mostly worked. It has a drawback,
> though: it's an incomplete implementation of the Iterator protocol. It's
> still (mostly) an Iterator, but not an Iterable, so it depends on how you
> use it whether you notice or not, and whether it works at all with other
> code or not. There's a test for a failing "next(coro)" in your test suite,
> for example, which would then not fail in Cython. [..]

I think if "next(cython_coro)" does not fail is acceptable.  It's not ideal, but
the purpose of Cython is to make Python code as fast as possible, so I'd try
to avoid having any kind of "thin wrappers" around Cyhton coroutines.
msg244322 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-28 16:59
Thanks Yury, I'll give it a try ASAP.
msg244374 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-29 13:08
Stefan,

Because of https://mail.python.org/pipermail/python-committers/2015-May/003410.html I've decided to commit 24315 and 24316 today.  Please try to check that everything works before new beta 2.
msg244384 - (view) Author: Stefan Behnel (scoder) * Date: 2015-05-29 15:09
Tried it, works for me. Thanks!
msg244385 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-05-29 15:14
> Tried it, works for me. Thanks!

This is really good news! Thanks!
msg244567 - (view) Author: Roundup Robot (python-dev) Date: 2015-06-01 01:37
New changeset 0708aabefb55 by Yury Selivanov in branch '3.4':
Issue 24017: Fix asyncio.CoroWrapper to support 'async def' coroutines
https://hg.python.org/cpython/rev/0708aabefb55

New changeset 1dc232783012 by Yury Selivanov in branch '3.5':
Issue 24017: Fix asyncio.CoroWrapper to support 'async def' coroutines
https://hg.python.org/cpython/rev/1dc232783012

New changeset 2e7c45560c38 by Yury Selivanov in branch 'default':
Issue 24017: Fix asyncio.CoroWrapper to support 'async def' coroutines
https://hg.python.org/cpython/rev/2e7c45560c38
msg244568 - (view) Author: Roundup Robot (python-dev) Date: 2015-06-01 01:44
New changeset a0a699b828e7 by Yury Selivanov in branch '3.5':
Issue 24017: Add a test for CoroWrapper and 'async def' coroutines
https://hg.python.org/cpython/rev/a0a699b828e7

New changeset 89521ac669f0 by Yury Selivanov in branch 'default':
Issue 24017: Add a test for CoroWrapper and 'async def' coroutines
https://hg.python.org/cpython/rev/89521ac669f0
msg244596 - (view) Author: Roundup Robot (python-dev) Date: 2015-06-01 16:16
New changeset 1e9e0664ee9b by Yury Selivanov in branch '3.5':
Issue 24017: Make PyEval_(Set|Get)CoroutineWrapper private
https://hg.python.org/cpython/rev/1e9e0664ee9b

New changeset 6fcb64097b1c by Yury Selivanov in branch 'default':
Issue 24017: Make PyEval_(Set|Get)CoroutineWrapper private
https://hg.python.org/cpython/rev/6fcb64097b1c
msg244759 - (view) Author: Alex Grönholm (alex.gronholm) * Date: 2015-06-03 15:16
Was __await__() deliberately left out of concurrent.futures.Future or was that an oversight? Or am I misunderstanding something?
msg244761 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-06-03 15:18
> Was __await__() deliberately left out of concurrent.futures.Future or was that an oversight? Or am I misunderstanding something?

I don't think concurrent.Future is supposed to be used with asyncio (in 'yield from' or 'await' expressions).
msg244799 - (view) Author: Stefan Behnel (scoder) * Date: 2015-06-04 05:30
Hmm, but IMHO a) the new syntax isn't just for asyncio and b) awaiting a Future seems like a *very* reasonable thing to do. I think opening a new ticket for this is a good idea.
msg244818 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-06-04 13:06
> Hmm, but IMHO a) the new syntax isn't just for asyncio and b) awaiting a Future seems like a *very* reasonable thing to do. I think opening a new ticket for this is a good idea.

Stefan, I honestly have bo idea what concurrent.Future.__await__ would do.  There is no loop for concurrent module.  If you have a patch with tests in mind, please open a separate issue (targeting 3.6).
msg244826 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2015-06-04 15:05
Maybe it's possible to give an interpretation to awaiting on a threaded
Future? __await__ could return a new asyncio Future, and add a completion
callback to the original Future that makes the asyncio Future ready and
transfers the result/exception. This would have to use
loop.call_soon_threadsafe() to transfer control from the exector thread to
the thread where the loop is running.

The only thing I don't know is whether it's possible for __await__ to
return a Future.
msg244831 - (view) Author: Yury Selivanov (yselivanov) * (Python committer) Date: 2015-06-04 15:38
Guido, Stefen, please see issue24383.
msg245075 - (view) Author: Stefan Behnel (scoder) * Date: 2015-06-09 17:11
See issue 24400 regarding a split of yield-based generators and async-def coroutines at a type level.
History
Date User Action Args
2015-06-20 19:39:53yselivanovsetdependencies: + Awaitable ABC incompatible with functools.singledispatch
2015-06-09 17:11:27scodersetmessages: + msg245075
2015-06-04 15:38:35yselivanovsetmessages: + msg244831
2015-06-04 15:05:57gvanrossumsetmessages: + msg244826
2015-06-04 13:06:12yselivanovsetmessages: + msg244818
2015-06-04 05:30:28scodersetmessages: + msg244799
2015-06-03 15:18:53yselivanovsetmessages: + msg244761
2015-06-03 15:16:08alex.gronholmsetnosy: + alex.gronholm
messages: + msg244759
2015-06-01 16:16:03python-devsetmessages: + msg244596
2015-06-01 01:44:22python-devsetmessages: + msg244568
2015-06-01 01:37:45python-devsetmessages: + msg244567
2015-05-29 15:14:35yselivanovsetmessages: + msg244385
2015-05-29 15:09:41scodersetmessages: + msg244384
2015-05-29 13:08:12yselivanovsetmessages: + msg244374
2015-05-28 16:59:00scodersetmessages: + msg244322
2015-05-28 16:42:29yselivanovsetdependencies: + Fix types.coroutine to accept objects from Cython
messages: + msg244319
2015-05-28 15:22:52python-devsetmessages: + msg244307
2015-05-28 15:13:46yselivanovsetdependencies: + collections.abc: Coroutine should be derived from Awaitable
2015-05-28 14:53:26python-devsetmessages: + msg244303
2015-05-28 06:48:01scodersetmessages: + msg244281
2015-05-28 06:28:36scodersetmessages: + msg244280
2015-05-28 06:15:15scodersetmessages: + msg244278
2015-05-28 05:35:53ncoghlansetmessages: + msg244273
2015-05-28 05:12:50yselivanovsetmessages: + msg244269
2015-05-28 05:10:10ncoghlansetmessages: + msg244268
2015-05-28 04:35:16yselivanovsetmessages: + msg244264
2015-05-28 04:18:30scodersetmessages: + msg244261
2015-05-28 03:59:56scodersetmessages: + msg244258
2015-05-28 03:54:41yselivanovsetmessages: + msg244257
2015-05-28 03:30:02scodersetmessages: + msg244252
2015-05-27 15:10:14python-devsetmessages: + msg244175
2015-05-21 16:03:49python-devsetmessages: + msg243759
2015-05-14 03:27:38yselivanovsetdependencies: + PEP 492: Add AsyncIterator and AsyncIterable to collections.abc
2015-05-13 20:49:55python-devsetmessages: + msg243119
2015-05-13 19:49:27gvanrossumsetmessages: + msg243118
2015-05-13 19:47:52yselivanovsetdependencies: + PEP 492: Documentation
2015-05-13 19:46:15yselivanovsetstatus: open -> closed
messages: + msg243117

components: + Interpreter Core
resolution: fixed
stage: patch review -> resolved
2015-05-13 06:06:45ncoghlansetmessages: + msg243042
2015-05-13 05:54:16python-devsetmessages: + msg243041
2015-05-13 05:19:52yselivanovsetmessages: + msg243038
2015-05-13 05:19:39ncoghlansetmessages: + msg243037
2015-05-13 05:15:50ncoghlansetmessages: + msg243036
2015-05-13 05:10:43yselivanovsetmessages: + msg243035
2015-05-13 05:00:58ncoghlansetmessages: + msg243033
2015-05-13 03:36:03yselivanovsetfiles: + with.patch

messages: + msg243031
2015-05-12 18:28:40python-devsetmessages: + msg242984
2015-05-12 15:46:02python-devsetmessages: + msg242982
2015-05-12 15:30:46python-devsetmessages: + msg242979
2015-05-12 04:06:39python-devsetmessages: + msg242938
2015-05-12 03:23:40gvanrossumsetmessages: + msg242937
2015-05-12 03:06:30yselivanovsetmessages: + msg242936
2015-05-12 03:03:22python-devsetmessages: + msg242935
2015-05-12 02:31:32python-devsetnosy: + python-dev
messages: + msg242931
2015-05-12 00:16:54ncoghlansetmessages: + msg242928
2015-05-12 00:03:04ncoghlansetmessages: + msg242927
2015-05-11 19:59:43yselivanovsetfiles: + await_06.patch

messages: + msg242912
2015-05-11 01:33:02yselivanovsetfiles: + await_05.patch

messages: + msg242877
2015-05-10 21:25:37yselivanovsetdependencies: + add a Generator ABC
2015-05-10 17:40:40asvetlovsetmessages: + msg242862
2015-05-10 16:21:44yselivanovsetmessages: + msg242860
2015-05-10 03:34:08ncoghlansetnosy: + ncoghlan
messages: + msg242848
2015-05-09 03:29:49scodersetmessages: + msg242793
2015-05-08 21:15:24yselivanovsetfiles: + await_04.patch

messages: + msg242779
2015-05-07 20:13:29yselivanovsetfiles: + await_03.patch

messages: + msg242731
2015-05-06 00:16:22yselivanovsetmessages: + msg242627
2015-05-06 00:05:54yselivanovsetpriority: normal -> release blocker
2015-05-06 00:05:25yselivanovsetdependencies: + Missing *-unpacking generalizations
2015-05-01 15:18:54gvanrossumsetmessages: + msg242326
2015-05-01 12:19:22scodersetmessages: + msg242304
2015-04-27 19:52:07gvanrossumsetnosy: + gvanrossum
2015-04-26 23:27:49yselivanovsetmessages: + msg242086
2015-04-26 17:27:56yselivanovsetmessages: + msg242064
2015-04-26 15:11:00scodersetmessages: + msg242056
2015-04-21 04:03:40yselivanovsetassignee: yselivanov
2015-04-21 03:59:19yselivanovsetfiles: + await_02.patch

messages: + msg241697
2015-04-21 00:53:09yselivanovsetdependencies: + PEP 479: Change StopIteration handling inside generators
2015-04-20 21:43:13hayposetmessages: + msg241687
2015-04-20 19:56:16yselivanovsetfiles: - await_01.patch
2015-04-20 19:55:43yselivanovsetfiles: + await_01.patch
2015-04-20 19:55:22yselivanovsetfiles: + await_01.patch

messages: + msg241679
2015-04-20 19:55:02yselivanovsetfiles: - async_01.patch
2015-04-20 19:45:38yselivanovsetfiles: + async_01.patch
keywords: + patch
messages: + msg241678

stage: patch review
2015-04-20 19:43:04hayposethgrepos: - hgrepo306
2015-04-20 19:38:45scodersetnosy: + scoder
type: enhancement
2015-04-20 19:37:47yselivanovsetnosy: + asvetlov, yselivanov
2015-04-20 19:34:02hayposethgrepos: + hgrepo306
2015-04-20 19:33:55haypocreate