Why does python asyncio loop.call_soon overwrite data?

后端 未结 3 1577
暗喜
暗喜 2021-01-27 11:51

I created a hard to track down bug in our code, but do not understand why it occurs. The problem occurs when pushing the same async function multiple times to call soon. It d

3条回答
  •  無奈伤痛
    2021-01-27 12:31

    In addition to correct explanations by others concerning the error in the lambda, also note that you don't even need the lambda. Since do_something is a coroutine, just calling it will not execute any of its code until the next iteration of the event loop, so you automatically have the effect of a call_soon. (This is analogous to how calling a generator function doesn't start executing it until you start exhausing the returned iterator.)

    In other words, you can replace

    self.loop.call_soon(lambda: asyncio.ensure_future(self.do_something(k, v)))
    

    with the simpler

    self.loop.create_task(self.do_something(k, v))
    

    create_task is preferable to ensure_future when you are dealing with a coroutine.

提交回复
热议问题