On this page
Futures
源代码: Lib/asyncio/futures.py,Lib/asyncio/base_futures.py
- Future *对象用于将“低级基于回调的代码”与高级异步/await 代码进行 bridge。
Future Functions
asyncio.
isfuture
(* obj *)- 如果* obj *是以下任意一个,则返回
True
:
- 如果* obj *是以下任意一个,则返回
asyncio.Future的实例,
asyncio.Task的实例,
具有
_asyncio_future_blocking
属性的类似 Future 的对象。
3.5 版中的新Function。
asyncio.
ensure_future
(* obj ,**,* loop = None *)- Return:
如果* obj 是Future,Task或类似 Future 的对象(isfuture()用于测试),则原样使用 obj *参数。
一个Task对象包装* obj ,如果 obj *是协程(iscoroutine()用于测试);在这种情况下,协程将由
ensure_future()
调度。如果* obj 是可 await 的,则将在 obj *上 await 的Task对象(测试使用inspect.isawaitable()。)
如果* obj *以上都不是,则引发TypeError。
Important
另请参见create_task()函数,这是创建新任务的首选方法。
在版本 3.5.1 中更改:该函数接受任何awaitable对象。
asyncio.
wrap_future
(* future ,**,* loop = None *)- 将concurrent.futures.Future对象包装在asyncio.Future对象中。
Future Object
-
- class *
asyncio.
Future
(**, loop = None *)
- Future 表示异步操作的finally结果。不是线程安全的。
- class *
Future 是awaitable对象。协程可以 awaitFuture 对象,直到它们具有结果或异常集,或者直到它们被取消为止。
通常,Futures 用于启用基于低级回调的代码(例如,在使用 asyncio transports实现的协议中)以与高级 async/await 代码进行互操作。
经验法则是永远不要在面向用户的 API 中公开 Future 对象,建议的创建 Future 对象的方法是调用loop.create_future()。这样,备用事件循环实现可以注入自己对 Future 对象的优化实现。
在 3.7 版中进行了更改:添加了对contextvars模块的支持。
result
( )- 返回 Future 的结果。
如果 Future 是* done *,并且具有passset_result()方法设置的结果,则返回结果值。
如果 Future 是* done *,并且具有set_exception()方法设置的异常,则此方法引发该异常。
如果 Future 已被* cancelled *取消,则此方法引发CancelledError异常。
如果 Future 的结果尚不可用,则此方法将引发InvalidStateError异常。
set_result
(结果)- 将 Future 标记为* done *,并设置其结果。
如果 Future 已经* done *,则引发InvalidStateError错误。
set_exception
(* exception *)- 将 Future 标记为* done *,并设置 exception。
如果 Future 已经* done *,则引发InvalidStateError错误。
done
( )- 如果 Future 是* done *,则返回
True
。
- 如果 Future 是* done *,则返回
如果期货被“取消”,或者其结果或设置了set_result()或set_exception()调用的异常,则“完成”为“完成”。
cancelled
( )- 如果取消了,则返回
True
。
- 如果取消了,则返回
该方法通常用于在设置结果或异常之前检查 Future 是否被“取消”。
if not fut.cancelled():
fut.set_result(42)
add_done_callback
(* callback ,**,* context = None *)- 添加一个在 Future 为* done *时运行的回调。
将以 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。
remove_done_callback
(回叫)- 从回调列表中删除* callback *。
返回删除的回调数,通常为 1,除非多次添加了回调。
cancel
( )- 取消将来并安排回调。
如果“将来”已经“完成”或“已取消”,请返回False
。否则,将 Future 的状态更改为* cancelled *,安排回调,并返回True
。
exception
( )- 返回在此 Future 上设置的异常。
仅当 Future 为* done *时,才会返回异常(如果未设置任何异常,则返回None
)。
如果 Future 已被* cancelled *取消,则此方法引发CancelledError异常。
如果 Future 还没有完成,则此方法引发InvalidStateError异常。
get_loop
( )- 返回 Future 对象绑定到的事件循环。
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。主要区别包括:
与 asyncio Futures 不同,无法 awaitconcurrent.futures.Future个实例。
asyncio.Future.result()和asyncio.Future.exception()不接受* timeout *参数。
当 Future 未完成*时asyncio.Future.result()和asyncio.Future.exception()引发InvalidStateError异常。
在asyncio.Future.add_done_callback()注册的回调不会立即被调用。他们改用loop.call_soon()安排。
asyncio Future 与concurrent.futures.wait()和concurrent.futures.as_completed()函数不兼容。