I was wondering if there's any library for asynchronous method calls in Python. It would be great if you could do something like
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alternative, polling
while not token.finished():
doSomethingElse()
if token.finished():
result = token.result()
Or to call a non-async routine asynchronously
def longComputation()
<code>
token = asynccall(longComputation())
It would be great to have a more refined strategy as native in the language core. Was this considered?
Just
My solution is:
And works exactly as requested:
Something like this works for me, you can then call the function, and it will dispatch itself onto a new thread.
It's not in the language core, but a very mature library that does what you want is Twisted. It introduces the Deferred object, which you can attach callbacks or error handlers ("errbacks") to. A Deferred is basically a "promise" that a function will have a result eventually.
As of Python 3.5, you can use enhanced generators for async functions.
Enhanced generator syntax:
New
async/await
syntax:You can use concurrent.futures (added in Python 3.2).