[Python-Dev] Tricky way of of creating a generator via a comprehension expression (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Sun Nov 26 21:01:52 EST 2017


On 27 November 2017 at 06:29, Nathaniel Smith <njs at pobox.com> wrote:

- In async/await, it's not obvious how to write leaf functions: 'await' is equivalent to 'yield from', but there's no equivalent to 'yield'. You have to jump through some hoops by writing a class with a custom await method or using @types.coroutine. Of course it's doable, and it's no big deal if you're writing a proper async library, but it's awkward for quick ad hoc usage.

For a concrete example of 'ad hoc coroutines' where I think 'yield from' is appropriate, here's wsproto's old 'yield from'-based incremental websocket protocol parser: https://github.com/python-hyper/wsproto/blob/4b7db502cc0568ab2354798552148dadd563a4e3/wsproto/frameprotocol.py#L142

sys.set_coroutine_wrapper itself is another case where you genuinely can't rely on async/await in the wrapper implementation.

The current example shown at https://docs.python.org/3/library/sys.html#sys.set_coroutine_wrapper is of a case that will fail, since it would otherwise result in infinite recursion when the coroutine wrapper attempts to call the coroutine wrapper.

Cheers, Nick.

P.S. Making that point reminded me that I still haven't got around to updating those docs to also include examples of how to do it right: https://bugs.python.org/issue30578

-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia



More information about the Python-Dev mailing list