Futures

源代码: Lib/asyncio/futures.pyLib/asyncio/base_futures.py


Future Functions

3.5 版中的新Function。

如果* obj *以上都不是,则引发TypeError

Important

另请参见create_task()函数,这是创建新任务的首选方法。

在版本 3.5.1 中更改:该函数接受任何awaitable对象。

Future Object

Future 是awaitable对象。协程可以 awaitFuture 对象,直到它们具有结果或异常集,或者直到它们被取消为止。

通常,Futures 用于启用基于低级回调的代码(例如,在使用 asyncio transports实现的协议中)以与高级 async/await 代码进行互操作。

经验法则是永远不要在面向用户的 API 中公开 Future 对象,建议的创建 Future 对象的方法是调用loop.create_future()。这样,备用事件循环实现可以注入自己对 Future 对象的优化实现。

在 3.7 版中进行了更改:添加了对contextvars模块的支持。

如果 Future 是* done *,并且具有passset_result()方法设置的结果,则返回结果值。

如果 Future 是* done *,并且具有set_exception()方法设置的异常,则此方法引发该异常。

如果 Future 已被* cancelled *取消,则此方法引发CancelledError异常。

如果 Future 的结果尚不可用,则此方法将引发InvalidStateError异常。

如果 Future 已经* done *,则引发InvalidStateError错误。

如果 Future 已经* done *,则引发InvalidStateError错误。

如果期货被“取消”,或者其结果或设置了set_result()set_exception()调用的异常,则“完成”为“完成”。

该方法通常用于在设置结果或异常之前检查 Future 是否被“取消”。

if not fut.cancelled():
    fut.set_result(42)

将以 Future 对象作为唯一参数来调用* callback *。

如果调用此方法时 Future 已经完成,则回调将passloop.call_soon()进行调度。

可选的仅关键字* context 参数允许为运行的 callback 指定自定义contextvars.Context。当未提供 context *时,将使用当前上下文。

functools.partial()可用于将参数传递给回调,例如:

# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))

在 3.7 版中进行了更改:添加了* context *仅关键字参数。有关更多详细信息,请参见 PEP 567

返回删除的回调数,通常为 1,除非多次添加了回调。

如果“将来”已经“完成”或“已取消”,请返回False。否则,将 Future 的状态更改为* cancelled *,安排回调,并返回True

仅当 Future 为* done *时,才会返回异常(如果未设置任何异常,则返回None)。

如果 Future 已被* cancelled *取消,则此方法引发CancelledError异常。

如果 Future 还没有完成,则此方法引发InvalidStateError异常。

3.7 版中的新Function。

本示例创建一个 Future 对象,创建并安排一个异步 Task 来为 Future 设置结果,并 await 直到 Future 获得结果:

async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())

Important

Future 对象被设计为模仿concurrent.futures.Future。主要区别包括:

首页