Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.Future

tasks

A low-level 'result will arrive later' object: you can await it, and the value is set with set_result() or set_exception(). asyncio.Task is built on it.

Syntax

fut = loop.create_future(); fut.set_result(value); value = await fut

This is not concurrent.futures.Future: that one lives in threads and is not awaited, whereas asyncio.Future is not thread-safe and is bound to a loop. A result is set exactly once — a second set_result(), or result() on a pending future, raises InvalidStateError. Create one with loop.create_future(); application code rarely needs it: create_task() runs work in the background and asyncio.Event signals between tasks.

Examples

import asyncio
async def main():
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    loop.call_later(0.01, fut.set_result, 42)  # кто-то положит результат позже
    print(await fut)  # → 42
    try:
        fut.set_result(43)
    except asyncio.InvalidStateError:
        print('результат уже есть')  # → результат уже есть
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy