[Python-ideas] A send() built-in function to drive coroutines

Guido van Rossum guido at python.org
Mon Feb 16 23:30:04 CET 2015


This is brought up from time to time. I believe it is based on a
misunderstanding of coroutines.

On Mon, Feb 16, 2015 at 4:53 AM, Luciano Ramalho <luciano at ramalho.org>
wrote:

> Coroutines are useless until primed by a next(my_coro) call. There are
> decorators to solve this by returning a primed coroutine. Such
> decorators add another problem: now the user may be unsure whether a
> specific coroutine from a third-party API should be primed or not
> prior to use.
>
> How about having a built-in function named send() with the signature
> send(coroutine, value) that does the right thing: sends a value to the
> coroutine, priming it if necessary. So instead of writing this:
>
> >>> next(my_coro)
> >>> my_coro.send(a_value)
>
> You could always write this:
>
> >>> send(my_coro, a_value)
>
> At a high level, the behavior of send() would be like this:
>
> def send(coroutine, value):
>     if inspect.getgeneratorstate() == 'GEN_CREATED':
>         next(coroutine)
>     coroutine.send(value)
>
> Consider the above pseudo-code. Proper handling of other generator
> states should be added.
>
> This would make coroutines easier to use, and would make their basic
> usage more consistent with the usage of plain generators using a
> function syntax -- eg. next(my_gen) -- instead of method call syntax.
>
> What do you think? If this has been discussed before, please send me a
> link (I searched but came up empty).
>
> Best,
>
> Luciano
>
>
>
> --
> Luciano Ramalho
> Twitter: @ramalhoorg
>
> Professor em: http://python.pro.br
> Twitter: @pythonprobr
> _______________________________________________
> 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/20150216/735b5d32/attachment.html>


More information about the Python-ideas mailing list