Futures¶
Source code:Lib/asyncio/futures.py,Lib/asyncio/base_futures.py
Future objects are used to bridgelow-level callback-based codewith high-level async/await code.
Future Functions¶
- asyncio.isfuture(obj)¶
Return
Trueifobj is either of:an instance of
asyncio.Future,an instance of
asyncio.Task,a Future-like object with a
_asyncio_future_blockingattribute.
Added in version 3.5.
- asyncio.ensure_future(obj,*,loop=None)¶
Return:
obj argument as is, ifobj is a
Future,aTask, or a Future-like object (isfuture()is used for the test.)a
Taskobject wrappingobj, ifobj is acoroutine (iscoroutine()is used for the test);in this case the coroutine will be scheduled byensure_future().a
Taskobject that would await onobj, ifobj is anawaitable (inspect.isawaitable()is used for the test.)
Ifobj is neither of the above a
TypeErroris raised.Important
Save a reference to the result of this function, to avoida task disappearing mid-execution.
See also the
create_task()function which is thepreferred way for creating new tasks or useasyncio.TaskGroupwhich keeps reference to the task internally.Changed in version 3.5.1:The function accepts anyawaitable object.
Deprecated since version 3.10:Deprecation warning is emitted ifobj is not a Future-like objectandloop is not specified and there is no running event loop.
- asyncio.wrap_future(future,*,loop=None)¶
Wrap a
concurrent.futures.Futureobject in aasyncio.Futureobject.Deprecated since version 3.10:Deprecation warning is emitted iffuture is not a Future-like objectandloop is not specified and there is no running event loop.
Future Object¶
- classasyncio.Future(*,loop=None)¶
A Future represents an eventual result of an asynchronousoperation. Not thread-safe.
Future is anawaitable object. Coroutines can await onFuture objects until they either have a result or an exceptionset, or until they are cancelled. A Future can be awaited multipletimes and the result is same.
Typically Futures are used to enable low-levelcallback-based code (e.g. in protocols implemented using asynciotransports)to interoperate with high-level async/await code.
The rule of thumb is to never expose Future objects in user-facingAPIs, and the recommended way to create a Future object is to call
loop.create_future(). This way alternative event loopimplementations can inject their own optimized implementationsof a Future object.Changed in version 3.7:Added support for the
contextvarsmodule.Deprecated since version 3.10:Deprecation warning is emitted ifloop is not specifiedand there is no running event loop.
- result()¶
Return the result of the Future.
If the Future isdone and has a result set by the
set_result()method, the result value is returned.If the Future isdone and has an exception set by the
set_exception()method, this method raises the exception.If the Future has beencancelled, this method raisesa
CancelledErrorexception.If the Future’s result isn’t yet available, this method raisesan
InvalidStateErrorexception.
- set_result(result)¶
Mark the Future asdone and set its result.
Raises an
InvalidStateErrorerror if the Future isalreadydone.
- set_exception(exception)¶
Mark the Future asdone and set an exception.
Raises an
InvalidStateErrorerror if the Future isalreadydone.
- done()¶
Return
Trueif the Future isdone.A Future isdone if it wascancelled or if it has a resultor an exception set with
set_result()orset_exception()calls.
- cancelled()¶
Return
Trueif the Future wascancelled.The method is usually used to check if a Future is notcancelled before setting a result or an exception for it:
ifnotfut.cancelled():fut.set_result(42)
- add_done_callback(callback,*,context=None)¶
Add a callback to be run when the Future isdone.
Thecallback is called with the Future object as its onlyargument.
If the Future is alreadydone when this method is called,the callback is scheduled with
loop.call_soon().An optional keyword-onlycontext argument allows specifying acustom
contextvars.Contextfor thecallback to run in.The current context is used when nocontext is provided.functools.partial()can be used to pass parametersto the callback, e.g.:# Call 'print("Future:", fut)' when "fut" is done.fut.add_done_callback(functools.partial(print,"Future:"))
Changed in version 3.7:Thecontext keyword-only parameter was added.SeePEP 567 for more details.
- remove_done_callback(callback)¶
Removecallback from the callbacks list.
Returns the number of callbacks removed, which is typically 1,unless a callback was added more than once.
- cancel(msg=None)¶
Cancel the Future and schedule callbacks.
If the Future is alreadydone orcancelled, return
False.Otherwise, change the Future’s state tocancelled,schedule the callbacks, and returnTrue.Changed in version 3.9:Added themsg parameter.
- exception()¶
Return the exception that was set on this Future.
The exception (or
Noneif no exception was set) isreturned only if the Future isdone.If the Future has beencancelled, this method raises a
CancelledErrorexception.If the Future isn’tdone yet, this method raises an
InvalidStateErrorexception.
- get_loop()¶
Return the event loop the Future object is bound to.
Added in version 3.7.
This example creates a Future object, creates and schedules anasynchronous Task to set result for the Future, and waits untilthe Future has a result:
asyncdefset_after(fut,delay,value):# Sleep for *delay* seconds.awaitasyncio.sleep(delay)# Set *value* as a result of *fut* Future.fut.set_result(value)asyncdefmain():# 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(awaitfut)asyncio.run(main())
Important
The Future object was designed to mimicconcurrent.futures.Future. Key differences include:
unlike asyncio Futures,
concurrent.futures.Futureinstances cannot be awaited.asyncio.Future.result()andasyncio.Future.exception()do not accept thetimeout argument.asyncio.Future.result()andasyncio.Future.exception()raise anInvalidStateErrorexception when the Future is notdone.Callbacks registered with
asyncio.Future.add_done_callback()are not called immediately. They are scheduled withloop.call_soon()instead.asyncio Future is not compatible with the
concurrent.futures.wait()andconcurrent.futures.as_completed()functions.asyncio.Future.cancel()accepts an optionalmsgargument,butconcurrent.futures.Future.cancel()does not.