源代码: Lib/asyncio/futures.py , Lib/asyncio/base_futures.py
Future 对象用于桥接 基于回调的低级代码 采用高级 async/await 代码。
返回
True
if
obj
是:
实例化的
asyncio.Future
,
实例化的
asyncio.Task
,
像 Future 对象具有
_asyncio_future_blocking
属性。
3.5 版新增。
返回:
obj
argument as is, if
obj
是
Future
,
Task
, or a Future-like object (
isfuture()
is used for the test.)
a
Task
object wrapping
obj
,若
obj
is a coroutine (
iscoroutine()
is used for the test); in this case the coroutine will be scheduled by
ensure_future()
.
a
Task
object that would await on
obj
,若
obj
is an awaitable (
inspect.isawaitable()
is used for the test.)
若
obj
is neither of the above a
TypeError
被引发。
重要
另请参阅
create_task()
function which is the preferred way for creating new Tasks.
Save a reference to the result of this function, to avoid a task disappearing mid-execution.
3.5.1 版改变: The function accepts any awaitable 对象。
从 3.10 版起弃用: Deprecation warning is emitted if obj is not a Future-like object and loop is not specified and there is no running event loop.
包裹
concurrent.futures.Future
对象在
asyncio.Future
对象。
从 3.10 版起弃用: Deprecation warning is emitted if future is not a Future-like object and loop is not specified and there is no running event loop.
A Future represents an eventual result of an asynchronous operation. Not thread-safe.
Future 是 awaitable object. Coroutines can await on Future objects until they either have a result or an exception set, or until they are cancelled. A Future can be awaited multiple times and the result is same.
Typically Futures are used to enable low-level callback-based code (e.g. in protocols implemented using asyncio 传输 ) to interoperate with high-level async/await code.
The rule of thumb is to never expose Future objects in user-facing APIs, and the recommended way to create a Future object is to call
loop.create_future()
. This way alternative event loop implementations can inject their own optimized implementations of a Future object.
3.7 版改变:
添加支持
contextvars
模块。
从 3.10 版起弃用: Deprecation warning is emitted if loop is not specified and there is no running event loop.
返回 Future 的结果。
若 Future 是
done
and has a result set by the
set_result()
method, the result value is returned.
若 Future 是
done
and has an exception set by the
set_exception()
method, this method raises the exception.
If the Future has been
cancelled
, this method raises a
CancelledError
异常。
If the Future’s result isn’t yet available, this method raises a
InvalidStateError
异常。
Mark the Future as done and set its result.
引发
InvalidStateError
error if the Future is already
done
.
Mark the Future as done and set an exception.
引发
InvalidStateError
error if the Future is already
done
.
返回
True
若 Future 是
done
.
A Future is
done
if it was
cancelled
or if it has a result or an exception set with
set_result()
or
set_exception()
调用。
返回
True
若 Future
cancelled
.
The method is usually used to check if a Future is not cancelled before setting a result or an exception for it:
if not fut.cancelled(): fut.set_result(42)
Add a callback to be run when the Future is done .
callback is called with the Future object as its only argument.
If the Future is already
done
when this method is called, the callback is scheduled with
loop.call_soon()
.
可选仅关键词
context
自变量允许指定自定义
contextvars.Context
为
callback
to run in. The current context is used when no
context
被提供。
functools.partial()
can be used to pass parameters to the callback, e.g.:
# Call 'print("Future:", fut)' when "fut" is done. fut.add_done_callback( functools.partial(print, "Future:"))
3.7 版改变: context keyword-only parameter was added. See PEP 567 了解更多细节。
移除 callback 从回调列表。
Returns the number of callbacks removed, which is typically 1, unless a callback was added more than once.
取消 Future 并调度回调。
If the Future is already
done
or
cancelled
,返回
False
. Otherwise, change the Future’s state to
cancelled
, schedule the callbacks, and return
True
.
3.9 版改变: 添加 msg 参数。
Return the exception that was set on this Future.
The exception (or
None
if no exception was set) is returned only if the Future is
done
.
If the Future has been
cancelled
, this method raises a
CancelledError
异常。
If the Future isn’t
done
yet, this method raises an
InvalidStateError
异常。
Return the event loop the Future object is bound to.
3.7 版新增。
This example creates a Future object, creates and schedules an asynchronous Task to set result for the Future, and waits until the Future has a result:
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())
重要
The Future object was designed to mimic
concurrent.futures.Future
. Key differences include:
不像 asyncio 未来,
concurrent.futures.Future
实例无法等待。
asyncio.Future.result()
and
asyncio.Future.exception()
do not accept the
timeout
自变量。
asyncio.Future.result()
and
asyncio.Future.exception()
raise an
InvalidStateError
exception when the Future is not
done
.
Callbacks registered with
asyncio.Future.add_done_callback()
are not called immediately. They are scheduled with
loop.call_soon()
代替。
asyncio Future is not compatible with the
concurrent.futures.wait()
and
concurrent.futures.as_completed()
函数。
asyncio.Future.cancel()
accepts an optional
msg
argument, but
concurrent.futures.cancel()
不会。