Asynchronous method call in Python?


I was wondering if there's any library for asynchronous method calls in Python. It would be great if you could do something like

def longComputation():

token = longComputation()
# alternative, polling
while not token.finished():
    if token.finished():
        result = token.result()

Or to call a non-async routine asynchronously

def longComputation()

token = asynccall(longComputation())

It would be great to have a more refined strategy as native in the language core. Was this considered?

10/31/2009 8:40:29 PM

Accepted Answer

You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:

apply_async(func[, args[, kwds[, callback]]])


from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.

11/18/2009 8:00:19 PM

Something like:

import threading

thr = threading.Thread(target=foo, args=(), kwargs={})
thr.start() # Will run "foo"
thr.is_alive() # Will return whether foo is running currently
thr.join() # Will wait till "foo" is done

See the documentation at for more details; this code should work for Python 3 as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow