Attend the Women in ML Symposium on December 7 Register now

tff.async_utils.SharedAwaitable

A wrapper allowing async functions to be awaited from multiple places.

async functions (those that start with async def) are typically awaited immediately at their callsite, as in await foo(). However, if users want to await this value from multiple async functions without running foo() twice, it can be useful to write something like this:

foo_coroutine = foo()

async def fn_one():
  ...
  x = await foo_coroutine
  ...

async def fn_two():
  ...
  x = await foo_coroutine
  ...

Unfortunately, directly awaiting the result of an async function multiple times is not supported, and will fail with an exception:

RuntimeError: cannot reuse already awaited coroutine

SharedAwaitable fixes this problem:

foo_coroutine = SharedAwaitable(foo())

async def fn_one():
  ...
  x = await foo_coroutine
  ...

async def fn_two():
  ...
  x = await foo_coroutine
  ...