3

When I call yield from some_coroutine() from with in a couroutine foo, is some_coroutine scheduled in the same even-loop as foo is currently running in? An example:

async def foo():
    yield from asyncio.sleep(5)

loop = asyncio.get_event_loop() # this could also be a custom event loop
loop.run_until_completed(foo())

In this example, in which event-loop will sleep be scheduled? I'm especially interested in the case where loop is not the default event-loop.

The documentation, under "Things a coroutine can do" says:

result = await coroutine or result = yield from coroutine – wait for another coroutine to produce a result (or raise an exception, which will be propagated). The coroutine expression must be a call to another coroutine.

It is not clear to me in which loop the coroutine will be scheduled.

1 Answer 1

3

Citing docs of get_event_loop

Get the event loop for the current context.

Implementation of default loop (Event loop default policy to be precise):

The default policy defines context as the current thread, and manages an event loop per thread that interacts with asyncio.

  • An event loop runs in a thread and executes all callbacks and tasks in the same thread (docs),

  • asyncio.get_event_loop returns the same loop for the same thread,

  • if you do not explicitly schedule on/interact with different thread's loop, it will use default (*) loop

In your example:

  1. get_event_loop returns current thread's event loop,

  2. foo is scheduled on that loop with run_until_completed

  3. any further async calls (awaits/yield from) are scheduled on the same loop

More info at Concurrency and multithreading.

(*) The event loop you called default is actually a loop of current thread.

2
  • Thank you very much, that clarifies it. I'm wondering though, since explicit is better than implicit, should explicitly passing the event loop be the preferred style? Jun 13, 2016 at 13:58
  • Should every function (e.g. file i/o) require a explicit thread passed (and dozen of other params)? keep the balance :)
    – kwarunek
    Jun 14, 2016 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.