Text of peps.python.org › pep-3148 as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 3148 – futures - execute computations asynchronously | peps.python.org

PEP 3148 – futures - execute computations asynchronously PEP 3148 – futures - execute computations asynchronously Author : Brian Quinlan <brian at sweetapp.com> Status : Final Type : Standards Track Created : 16-Oct-2009 Python-Version : 3.2 Post-History : Table of Contents Abstract Motivation Specification Naming Interface Executor ProcessPoolExecutor ThreadPoolExecutor Future Objects Internal Future Methods Module Functions Check Prime Example Web Crawl Example Rationale Reference Implementation References Copyright Abstract This PEP proposes a design for a package that facilitates the evaluation of callables using threads and processes.

Motivation Python currently has powerful primitives to construct multi-threaded and multi-process applications but parallelizing simple operations requires a lot of work i.e. explicitly launching processes/threads, constructing a work/results queue, and waiting for completion or some other termination condition (e.g. failure, timeout). It is also difficult to design an application with a global process/thread limit when each component invents its own parallel execution strategy.

Specification Naming The proposed package would be called “futures” and would live in a new “concurrent” top-level package. The rationale behind pushing the futures library into a “concurrent” namespace has multiple components. The first, most simple one is to prevent any and all confusion with the existing “from __future__ import x” idiom which has been in use for a long time within Python. Additionally, it is felt that adding the “concurrent” precursor to the name fully denotes what the library is related to - namely concurrency - this should clear up any addition ambiguity as it has been noted that not everyone in the community is familiar with Java Futures, or the Futures term except as it relates to the US stock market.

Finally; we are carving out a new namespace for the standard library - obviously named “concurrent”. We hope to either add, or move existing, concurrency-related libraries to this in the future. A prime example is the multiprocessing.Pool work, as well as other “addons” included in that module, which work across thread and process boundaries. Interface The proposed package provides two core classes: Executor and Future .

An Executor receives asynchronous work requests (in terms of a callable and its arguments) and returns a Future to represent the execution of that work request. Executor Executor is an abstract class that provides methods to execute calls asynchronously. submit(fn, *args, **kwargs) Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. This is an abstract method and must be implemented by Executor subclasses. map(func, *iterables, timeout=None) Equivalent to map(func, *iterables) but func is executed asynchronously and several calls to func may be made concurrently.

The returned iterator raises a TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to map() . If timeout is not specified or None then there is no limit to the wait time. If a call raises an exception then that exception will be raised when its value is retrieved from the iterator. shutdown(wait=True) Signal the executor that it should free any resources that it is using when the currently pending futures are done executing.

Calls to Executor.submit and Executor.map and made after shutdown will raise RuntimeError . If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing. __enter__() __exit__(exc_type, exc_val, exc_tb) When using an executor as a context manager, __exit__ will call Executor.shutdown(wait=True) .

ProcessPoolExecutor The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. The callable objects and arguments passed to ProcessPoolExecutor.submit must be pickleable according to the same limitations as the multiprocessing module. Calling Executor or Future methods from within a callable submitted to a ProcessPoolExecutor will result in deadlock. __init__(max_workers) Executes calls asynchronously using a pool of a most max_workers processes.

If max_workers is None or not given then as many worker processes will be created as the machine has processors. ThreadPoolExecutor The ThreadPoolExecutor class is an Executor subclass that uses a pool of threads to execute calls asynchronously. Deadlock can occur when the callable associated with a Future waits on the results of another Future . For example: import time def wait_on_b (): time . sleep ( 5 ) print ( b . result ()) # b will never complete because it is waiting on a. return 5 def wait_on_a (): time . sleep ( 5 ) print ( a . result ()) # a will never complete because it is waiting on b. return 6 executor = ThreadPoolExecutor ( max_workers = 2 ) a = executor . submit ( wait_on_b ) b = executor . submit ( wait_on_a ) And: def wait_on_future (): f = executor . submit ( pow , 5 , 2 ) # This will never complete because there is only one worker thread and # it is executing this function. print ( f . result ()) executor = ThreadPoolExecutor ( max_workers = 1 ) executor . submit ( wait_on_future ) __init__(max_workers) Executes calls asynchronously using a pool of at most max_workers threads.

Future Objects The Future class encapsulates the asynchronous execution of a callable. Future instances are returned by Executor.submit . cancel() Attempt to cancel the call. If the call is currently being executed then it cannot be cancelled and the method will return False , otherwise the call will be cancelled and the method will return True . cancelled() Return True if the call was successfully cancelled. running() Return True if the call is currently being executed and cannot be cancelled. done() Return True if the call was successfully cancelled or finished running. result(timeout=None) Return the value returned by the call.

If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds then a TimeoutError will be raised. If timeout is not specified or None then there is no limit to the wait time. If the future is cancelled before completing then CancelledError will be raised. If the call raised then this method will raise the same exception. exception(timeout=None) Return the exception raised by the call.

If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds then a TimeoutError will be raised. If timeout is not specified or None then there is no limit to the wait time. If the future is cancelled before completing then CancelledError will be raised. If the call completed without raising then None is returned. add_done_callback(fn) Attaches a callable fn to the future that will be called when the future is cancelled or finishes running. fn will be called with the future as its only argument.

Added callables are called in the order that they were added and are always called in a thread belonging to the process that added them. If the callable raises an Exception then it will be logged and ignored. If the callable raises another BaseException then behavior is not defined. If the future has already completed or been cancelled then fn will be called immediately. Internal Future Methods The following Future methods are meant for use in unit tests and Executor implementations. set_running_or_notify_cancel() Should be called by Executor imp

The rest of this page is on the live site.