The futures module provides a high-level interface for asynchronously executing functions and methods.
The asynchronous execution can be be performed by threads, using ThreadPoolExecutor, or seperate processes, using ProcessPoolExecutor. Both implement the same interface, which is defined by the abstract Executor class.
Executor is an abstract class that provides methods to execute calls asynchronously. It should not be used directly, but through its two subclasses: ThreadPoolExecutor and ProcessPoolExecutor.
Schedule the given calls for execution and return a FutureList containing a Future for each call. This method should always be called using keyword arguments, which are:
calls must be a sequence of callables that take no arguments.
timeout can be used to control the maximum number of seconds to wait before returning. If timeout is not specified or None then there is no limit to the wait time.
return_when indicates when the method should return. It must be one of the following constants:
Constant Description FIRST_COMPLETED The method will return when any call finishes. FIRST_EXCEPTION The method will return when any call raises an exception or when all calls finish. ALL_COMPLETED The method will return when all calls finish. RETURN_IMMEDIATELY The method will return immediately.
The ThreadPoolExecutor class is an Executor subclass that uses a pool of threads to execute calls asynchronously.
import functools
import urllib.request
import futures
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
def load_url(url, timeout):
return urllib.request.urlopen(url, timeout=timeout).read()
with futures.ThreadPoolExecutor(50) as executor:
future_list = executor.run_to_futures(
[functools.partial(load_url, url, 30) for url in URLS])
for url, future in zip(URLS, future_list):
if future.exception() is not None:
print('%r generated an exception: %s' % (url, future.exception()))
else:
print('%r page is %d bytes' % (url, len(future.result())))
The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
with futures.ProcessPoolExecutor() as executor:
for number, is_prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, is_prime))
The FutureList class is an immutable container for Future instances and should only be instantiated by Executor.run_to_futures().
Wait until the given conditions are met. This method should always be called using keyword arguments, which are:
timeout can be used to control the maximum number of seconds to wait before returning. If timeout is not specified or None then there is no limit to the wait time.
return_when indicates when the method should return. It must be one of the following constants:
Constant Description FIRST_COMPLETED The method will return when any call finishes. FIRST_EXCEPTION The method will return when any call raises an exception or when all calls finish. ALL_COMPLETED The method will return when all calls finish. RETURN_IMMEDIATELY The method will return immediately. This option is only available for consistency with Executor.run_to_results() and is not likely to be useful.
The Future class encapulates the asynchronous execution of a function or method call. Future instances are created by the Executor.run_to_futures() and bundled into a FutureList.
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.
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.