tornado.concurrent — Work with Future objects

Utilities for working with Future objects.

Tornado previously provided its own Future class, but now uses asyncio.Future. This module contains utility functions for working with asyncio.Future in a way that is backwards-compatible with Tornado’s old Future implementation.

While this module is an important part of Tornado’s internal implementation, applications rarely need to interact with it directly.

class tornado.concurrent.Future

tornado.concurrent.Future is an alias for asyncio.Future.

In Tornado, the main way in which applications interact with Future objects is by awaiting or yielding them in coroutines, instead of calling methods on the Future objects themselves. For more information on the available methods, see the asyncio.Future docs.

Changed in version 5.0: Tornado’s implementation of Future has been replaced by the version from asyncio when available.

  • Future objects can only be created while there is a current IOLoop

  • The timing of callbacks scheduled with Future.add_done_callback has changed.

  • Cancellation is now partially supported (only on Python 3)

  • The exc_info and set_exc_info methods are no longer available on Python 3.

class tornado.concurrent.Future

This class is almost compatible with concurrent.futures.Future.

Differences:

  • result() and exception() do not take a timeout argument and raise an exception when the future isn’t done yet.

  • Callbacks registered with add_done_callback() are always called via the event loop’s call_soon_threadsafe().

  • This class is not compatible with the wait() and as_completed() methods in the concurrent.futures package.

add_done_callback()

Add a callback to be run when the future becomes done.

The callback is called with a single argument - the future object. If the future is already done when this is called, the callback is scheduled with call_soon.

cancel()

Cancel the future and schedule callbacks.

If the future is already done or cancelled, return False. Otherwise, change the future’s state to cancelled, schedule the callbacks and return True.

cancelled()

Return True if the future was cancelled.

done()

Return True if the future is done.

Done means either that a result / exception are available, or that the future was cancelled.

exception()

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, raises CancelledError. If the future isn’t done yet, raises InvalidStateError.

get_loop()

Return the event loop the Future is bound to.

remove_done_callback()

Remove all instances of a callback from the “call when done” list.

Returns the number of callbacks removed.

result()

Return the result this future represents.

If the future has been cancelled, raises CancelledError. If the future’s result isn’t yet available, raises InvalidStateError. If the future is done and has an exception set, this exception is raised.

set_exception()

Mark the future done and set an exception.

If the future is already done when this method is called, raises InvalidStateError.

set_result()

Mark the future done and set its result.

If the future is already done when this method is called, raises InvalidStateError.

tornado.concurrent.run_on_executor(*args, **kwargs) → Callable[source]

Decorator to run a synchronous method asynchronously on an executor.

The decorated method may be called with a callback keyword argument and returns a future.

The executor to be used is determined by the executor attributes of self. To use a different attribute name, pass a keyword argument to the decorator:

@run_on_executor(executor='_thread_pool')
def foo(self):
    pass

This decorator should not be confused with the similarly-named IOLoop.run_in_executor. In general, using run_in_executor when calling a blocking method is recommended instead of using this decorator when defining a method. If compatibility with older versions of Tornado is required, consider defining an executor and using executor.submit() at the call site.

Changed in version 4.2: Added keyword arguments to use alternative attributes.

Changed in version 5.0: Always uses the current IOLoop instead of self.io_loop.

Changed in version 5.1: Returns a Future compatible with await instead of a concurrent.futures.Future.

Deprecated since version 5.1: The callback argument is deprecated and will be removed in 6.0. The decorator itself is discouraged in new code but will not be removed in 6.0.

Changed in version 6.0: The callback argument was removed.

tornado.concurrent.chain_future(a: Future[_T], b: Future[_T]) → None[source]

Chain two futures together so that when one completes, so does the other.

The result (success or failure) of a will be copied to b, unless b has already been completed or cancelled by the time a finishes.

Changed in version 5.0: Now accepts both Tornado/asyncio Future objects and concurrent.futures.Future.

tornado.concurrent.future_set_result_unless_cancelled(future: Union[futures.Future[_T], Future[_T]], value: _T) → None[source]

Set the given value as the Future’s result, if not cancelled.

Avoids asyncio.InvalidStateError when calling set_result() on a cancelled asyncio.Future.

New in version 5.0.

tornado.concurrent.future_set_exception_unless_cancelled(future: Union[futures.Future[_T], Future[_T]], exc: BaseException) → None[source]

Set the given exc as the Future’s exception.

If the Future is already canceled, logs the exception instead. If this logging is not desired, the caller should explicitly check the state of the Future and call Future.set_exception instead of this wrapper.

Avoids asyncio.InvalidStateError when calling set_exception() on a cancelled asyncio.Future.

New in version 6.0.

tornado.concurrent.future_set_exc_info(future: Union[futures.Future[_T], Future[_T]], exc_info: Tuple[Optional[type], Optional[BaseException], Optional[traceback]]) → None[source]

Set the given exc_info as the Future’s exception.

Understands both asyncio.Future and the extensions in older versions of Tornado to enable better tracebacks on Python 2.

New in version 5.0.

Changed in version 6.0: If the future is already cancelled, this function is a no-op. (previously asyncio.InvalidStateError would be raised)

tornado.concurrent.future_add_done_callback(future: Union[futures.Future[_T], Future[_T]], callback: Callable[[...], None]) → None[source]

Arrange to call callback when future is complete.

callback is invoked with one argument, the future.

If future is already done, callback is invoked immediately. This may differ from the behavior of Future.add_done_callback, which makes no such guarantee.

New in version 5.0.