2025-09-10:仓库迁移
This commit is contained in:
48
7.函数/11.内联回调函数.py
Normal file
48
7.函数/11.内联回调函数.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# 如果我们像上一节一样写一堆小函数在代码里,相信我你很快就会暴毙
|
||||
# 我们希望我们的内敛回调看起来比较正常
|
||||
# 我们有这样一个函数来调用回调:
|
||||
def apply_async(func, args, *, callback):
|
||||
result = func(*args)
|
||||
callback(result)
|
||||
|
||||
from queue import Queue
|
||||
from functools import wraps
|
||||
|
||||
class Async:
|
||||
def __init__(self, func, args):
|
||||
self.func = func
|
||||
self.args = args
|
||||
|
||||
def inline_async(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args):
|
||||
f = func(*args)
|
||||
result_queue = Queue()
|
||||
result_queue.put(None)
|
||||
while True:
|
||||
result = result_queue.get()
|
||||
try:
|
||||
a = f.send(result)
|
||||
apply_async(a.func, a.args, callback=f.send)
|
||||
except StopIteration:
|
||||
break
|
||||
return wrapper
|
||||
|
||||
def add(x, y):
|
||||
return x + y
|
||||
|
||||
@inline_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("Bye")
|
||||
|
||||
|
||||
# 这个东西比较高级,一般不使用这种方法,会让代码可读性变差
|
||||
# 拒绝个人炫技,回归可读本质,从你我做起
|
||||
test()
|
Reference in New Issue
Block a user