Asyncio -- delayed calculation

Ian Kelly ian.g.kelly at gmail.com
Tue Nov 29 13:41:45 EST 2016


On Mon, Nov 28, 2016 at 10:42 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Tue, Nov 29, 2016 at 4:13 PM, Paul Rubin <no.email at nospam.invalid> wrote:
>>
>> I haven't gotten my head around Python asyncio and have been wanting
>> to read this:
>>
>>    http://lucumr.pocoo.org/2016/10/30/i-dont-understand-asyncio/
>
> It's talking a lot about how we got here, which isn't all necessary if
> you just want to give asyncio a whirl. The conclusion at the end says
> that you should just use 'async def' and not bother with all the older
> forms, which I agree with (subject to the usual caveat that this
> implies no support for older Pythons).
>
> There's one thing that I really struggle with, though, and that's that
> there's no easy and obvious way to demonstrate the lowest level of
> operation. If "await x()" is like "yield from x()", how do you do the
> innermost "yield" that actually does something? I have the same
> confusion with Node.js, too. It's as if async primitives can't be
> implemented in application code at all, they just have to be given to
> you. Certainly it's not something made clear anywhere in the docs that
> I've found.

You mean how do you create something that can be awaited that doesn't
await something else in turn? With a Future.

import asyncio

class Awaitable(asyncio.Future):
  def wake_up_later(self):
    asyncio.get_event_loop().call_later(3, self.set_result, 42)

async def main():
  awaitable = Awaitable()
  awaitable.wake_up_later()
  print(await awaitable)

asyncio.get_event_loop().run_until_complete(main())

The trick is in arranging for the future's result to be set. For I/O
events you would typically do that by associating a callback with a
file descriptor on the event loop:

https://docs.python.org/3/library/asyncio-eventloop.html#watch-file-descriptors

If you need to do something particulary abstruse you can always write
a custom Selector or event loop:

https://docs.python.org/3/library/selectors.html#module-selectors
https://docs.python.org/3/library/asyncio-eventloop.html#base-event-loop



More information about the Python-list mailing list