[Python-ideas] Learning from the shell in supporting asyncio background calls

Nick Coghlan ncoghlan at gmail.com
Sat Jul 11 06:33:24 CEST 2015

On 10 July 2015 at 21:48, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> Why is that better than something like:
>      data1, data2 = asyncio.run([future1, future2])
> IIUC your proposal is that run_in_background adds the tasks to an
> implicit global variable.

It just schedules them normally using
asyncio.get_event_loop().create_task() (or run_in_executor if you pass
in a callable).

For folks that don't want to click through to the blog post (which has
a full worked example using asynchronous timers), the full
implementations of the two functions (with a slight tweak to
run_in_background to make the executor configurable as well) are:

  def run_in_background(target, *, loop=None, executor=None):
    if loop is None:
        loop = asyncio.get_event_loop()
        return asyncio.ensure_future(target, loop=loop)
    except TypeError:
    if callable(target):
        return loop.run_in_executor(executor, target)
    raise TypeError("background task must be future, coroutine or "
                    "callable, not {!r}".format(type(target)))

  def run_in_foreground(task, *, loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()
    return loop.run_until_complete(asyncio.ensure_future(task))

> Then the first call to run_in_foreground
> runs both tasks returning when future1 is ready. At that point it
> suspends future2 if incomplete? Then the second call to
> run_in_foreground returns immediately if future2 is ready or otherwise
> runs that task until complete?

No, it's all driven by the main asyncio event loop - the suggested
functions are relatively thin shims designed to let people make
effective use of asyncio with just the POSIX shell foreground &
background task mental model, rather than having to learn how asyncio
*really* works in order to benefit from it.


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

More information about the Python-ideas mailing list