mode.utils.futures — mode-ng 0.4.0 documentation

# `mode.utils.futures`

Async I/O Future utilities.

mode.utils.futures.done_future(result: Optional[Any] = None, *, loop: Optional[AbstractEventLoop] = None) → Future

  Return `asyncio.Future` that is already evaluated.

async mode.utils.futures.maybe_async(res: Any) → Any

  Await future if argument is Awaitable.

  Examples

      >>> await maybe_async(regular_function(arg))
      >>> await maybe_async(async_function(arg))

mode.utils.futures.maybe_cancel(fut: _asyncio.Future | None) → bool

  Cancel future if it is cancellable.

mode.utils.futures.maybe_set_exception(fut: _asyncio.Future | None, exc: BaseException) → bool

  Set future exception if not already done.

mode.utils.futures.maybe_set_result(fut: _asyncio.Future | None, result: Any) → bool

  Set future result if not already done.

mode.utils.futures.notify(fut: _asyncio.Future | None, result: Optional[Any] = None) → None

  Set `asyncio.Future` result if future exists and is not done.

class mode.utils.futures.stampede(fget: Callable, *, doc: Optional[str] = None)

  Descriptor for cached async operations providing stampede protection.

  See also thundering herd problem.

  Adding the decorator to an async callable method:

  Examples

  Here’s an example coroutine method connecting a network client:

      class Client:

          @stampede
          async def maybe_connect(self):
              await self._connect()

          async def _connect(self):
              return Connection()

  In the above example, if multiple coroutines call `maybe_connect` at the same time, then only one of them will actually perform the operation. The rest of the coroutines will wait for the result, and return it once the first caller returns.