我们正在编写使用回调函数的代码,但是担心小型函数在代码中大肆泛滥,程序的控制流会因此而失控。我们希望能有某种方法使代码看起来更像一般的过程式步骤。 我们可以通过生成器和协程将回调函数内联到一个函数中。
具体代码如下:
def apply_async(function, val, *, callback):
# Compute the result
result = function(*val)
#Invoke the callback with the result
callback(result)
from queue import Queue
from functools import wraps
class Async:
def __init__(self, function, args):
self.function = function
self.args = args
def in_lined_async(function):
@wraps(function)
def wrapper(*args):
f = function(*args)
result_queue = Queue()
result_queue.put(None)
while True:
result = result_queue.get()
try:
a = f.send(result)
apply_async(a.function, a.args, callback=result_queue.put)
except StopIteration:
break
return wrapper
def add(x, y):return x+y
@in_lined_async
def test():
r = yield Async(add, (2, 3))
print(r)
r = yield Async(add, ("Hello ", "World"))
print(r)
for n in range(5):
r = yield Async(add, (n, n))
print(r)
print("Goodbye")