mode.utils.futures

Async I/O Future utilities.

mode.utils.futures.all_tasks(loop: asyncio.events.AbstractEventLoop) → Set[_asyncio.Task]
mode.utils.futures.current_task()

Return the currently running task in an event loop or None.

By default the current task for the current event loop is returned.

None is returned when called not in the context of a Task.

class mode.utils.futures.stampede(fget: Callable, *, doc: 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.

mode.utils.futures.done_future(result: Any = None, *, loop: asyncio.events.AbstractEventLoop = None) → _asyncio.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: Optional[_asyncio.Future]) → bool

Cancel future if it is cancellable.

mode.utils.futures.maybe_set_exception(fut: Optional[_asyncio.Future], exc: BaseException) → bool

Set future exception if not already done.

mode.utils.futures.maybe_set_result(fut: Optional[_asyncio.Future], result: Any) → bool

Set future result if not already done.

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

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