Asyncio -- delayed calculation

Ian Kelly ian.g.kelly at gmail.com
Mon Nov 28 10:53:00 EST 2016


On Mon, Nov 28, 2016 at 5:48 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> Let's pretend that the computation can be performed asynchronously, so that
> I can have all five Counter objects counting down in parallel. I have this:
>
>
> import asyncio
>
> class Counter:
>     def __init__(self):
>         self.count = 10
>     async def count_down(self):
>         print(self, "starting")
>         while self.count > 0:
>             # simulate a computation
>             await asyncio.sleep(0.5)
>             self.count -= 1
>         print(self, "completed")
>
> async def main():
>     pool = [Counter() for i in range(5)]
>     for obj in pool:
>         obj.count_down()
>
> loop = asyncio.get_event_loop()
> loop.run_until_complete(main())
>
>
>
>
> When I try running that, I get no output. No error, no exception, the
> run_until_complete simply returns instantly.
>
> What am I doing wrong?

Remember that coroutines are basically generators. Native "async def"
coroutines are dressed up as something different, but they were still
designed as a drop-in replacement for generator coroutines. If
count_down were a generator function then simply calling it wouldn't
really do anything and as a native coroutine it still doesn't (other
than return a "coroutine object").

In order for the coroutines to actually do anything, you need to
schedule them in some way with the event loop. That could take the
form of awaiting them from some other coroutine, or passing them
directly to loop.run_until_complete or event_loop.create_task, or as
Chris suggested awaiting them as an aggregate.



More information about the Python-list mailing list