Skip to content

Commit 40b1526

Browse files
committed
7.11小节完成~
1 parent d71c38b commit 40b1526

File tree

4 files changed

+259
-3
lines changed

4 files changed

+259
-3
lines changed
File renamed without changes.

basic/myfunc/yield_send.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: 使用yield和send的典型场景
5+
Desc :
6+
get_primes的后几行需要着重解释。yield关键字返回number的值,而像 other = yield foo 这样的语句的意思是,
7+
"返回foo的值,这个值返回给调用者的同时,将other的值也设置为那个值"。
8+
你可以通过send方法来将一个值”发送“给生成器,这时候就是将other值设置为发送的值了。
9+
def get_primes(number):
10+
while True:
11+
if is_prime(number):
12+
number = yield number
13+
number += 1
14+
通过这种方式,我们可以在每次执行yield的时候为number设置不同的值。
15+
现在我们可以补齐print_successive_primes中缺少的那部分代码:
16+
def print_successive_primes(iterations, base=10):
17+
prime_generator = get_primes(base)
18+
prime_generator.send(None)
19+
for power in range(iterations):
20+
print(prime_generator.send(base ** power))
21+
这里有两点需要注意:
22+
首先,我们打印的是generator.send的结果,这是没问题的,
23+
因为send在发送数据给生成器的同时还返回生成器通过yield生成的值(就如同生成器中yield语句做的那样)。
24+
第二点,看一下prime_generator.send(None)这一行,
25+
当你用send来“启动”一个生成器时(就是从生成器函数的第一行代码执行到第一个yield语句的位置),
26+
你必须发送None。这不难理解,根据刚才的描述,生成器还没有走到第一个yield语句,
27+
如果我们发送一个真实的值,这时是没有人去“接收”它的。一旦生成器启动了,我们就可以像上面那样发送数据了。
28+
"""
29+
import random
30+
31+
32+
def get_data():
33+
"""返回0到9之间的3个随机数"""
34+
return random.sample(range(10), 3)
35+
36+
37+
def consume():
38+
"""显示每次传入的整数列表的动态平均值"""
39+
running_sum = 0
40+
data_items_seen = 0
41+
42+
while True:
43+
print('before 1 yield....')
44+
data = yield [0, 0, 0]
45+
print('-------yield inner------- {}'.format(data))
46+
print('after 1 yield...')
47+
data_items_seen += len(data)
48+
running_sum += sum(data)
49+
print('The running average is {} - {} - {}'.format(
50+
data_items_seen, running_sum, running_sum / float(data_items_seen)))
51+
52+
53+
def produce(consumer):
54+
"""产生序列集合,传递给消费函数(consumer)"""
55+
while True:
56+
data = get_data()
57+
print('Produced {}'.format(data))
58+
consumer.send(data)
59+
yield
60+
61+
62+
if __name__ == '__main__':
63+
consumer = consume()
64+
aa = consumer.send(None)
65+
print(aa)
66+
bb = consumer.send(get_data())
67+
print(bb)
68+
producer = produce(consumer)
69+
# for _ in range(2):
70+
# print('Producing...')
71+
# next(producer)

cookbook/c07/p11_inline_callback.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: 内联回调函数
5+
Desc :
6+
"""
7+
from queue import Queue
8+
from functools import wraps
9+
10+
11+
def apply_async(func, args, *, callback):
12+
# Compute the result
13+
result = func(*args)
14+
15+
# Invoke the callback with the result
16+
callback(result)
17+
18+
19+
class Async:
20+
def __init__(self, func, args):
21+
self.func = func
22+
self.args = args
23+
24+
25+
def inlined_async(func):
26+
@wraps(func)
27+
def wrapper(*args):
28+
f = func(*args)
29+
result_queue = Queue()
30+
result_queue.put(None)
31+
while True:
32+
print('1' * 15)
33+
result = result_queue.get()
34+
print('2' * 15)
35+
try:
36+
print('3' * 15)
37+
print('result={}'.format(result))
38+
a = f.send(result)
39+
print('4' * 15)
40+
apply_async(a.func, a.args, callback=result_queue.put)
41+
print('5' * 15)
42+
except StopIteration:
43+
break
44+
45+
return wrapper
46+
47+
48+
def add(x, y):
49+
return x + y
50+
51+
52+
@inlined_async
53+
def test():
54+
print('start'.center(20, '='))
55+
r = yield Async(add, (2, 3))
56+
print('last={}'.format(r))
57+
r = yield Async(add, ('hello', 'world'))
58+
print('last={}'.format(r))
59+
# for n in range(10):
60+
# r = yield Async(add, (n, n))
61+
# print(r)
62+
# print('Goodbye')
63+
print('end'.center(20, '='))
64+
65+
66+
if __name__ == '__main__':
67+
test()

source/c07/p11_inline_callback_functions.rst

Lines changed: 121 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,132 @@
55
----------
66
问题
77
----------
8-
todo...
8+
当你编写使用回调函数的代码的时候,担心很多小函数的扩张可能会弄乱程序控制流。
9+
你希望找到某个方法来让代码看上去更像是一个普通的执行序列。
10+
11+
|
912
1013
----------
1114
解决方案
1215
----------
13-
todo...
16+
通过使用生成器和协程可以使得回调函数内联在某个函数中。
17+
为了演示说明,假设你有如下所示的一个执行某种计算任务然后调用一个回调函数的函数(参考7.10小节):
18+
19+
.. code-block:: python
20+
21+
def apply_async(func, args, *, callback):
22+
# Compute the result
23+
result = func(*args)
24+
25+
# Invoke the callback with the result
26+
callback(result)
27+
28+
接下来让我们看一下下面的代码,它包含了一个 ``Async`` 类和一个 ``inlined_async`` 装饰器:
29+
30+
.. code-block:: python
31+
32+
from queue import Queue
33+
from functools import wraps
34+
35+
class Async:
36+
def __init__(self, func, args):
37+
self.func = func
38+
self.args = args
39+
40+
def inlined_async(func):
41+
@wraps(func)
42+
def wrapper(*args):
43+
f = func(*args)
44+
result_queue = Queue()
45+
result_queue.put(None)
46+
while True:
47+
result = result_queue.get()
48+
try:
49+
a = f.send(result)
50+
apply_async(a.func, a.args, callback=result_queue.put)
51+
except StopIteration:
52+
break
53+
return wrapper
54+
55+
这两个代码片段允许你使用 ``yield`` 语句内联回调步骤。比如:
56+
57+
.. code-block:: python
58+
59+
def add(x, y):
60+
return x + y
61+
62+
@inlined_async
63+
def test():
64+
r = yield Async(add, (2, 3))
65+
print(r)
66+
r = yield Async(add, ('hello', 'world'))
67+
print(r)
68+
for n in range(10):
69+
r = yield Async(add, (n, n))
70+
print(r)
71+
print('Goodbye')
72+
73+
如果你调用 ``test()`` ,你会得到类似如下的输出:
74+
75+
.. code-block:: python
76+
77+
5
78+
helloworld
79+
0
80+
2
81+
4
82+
6
83+
8
84+
10
85+
12
86+
14
87+
16
88+
18
89+
Goodbye
90+
91+
你会发现,除了那个特别的装饰器和 ``yield`` 语句外,其他地方并没有出现任何的回调函数(其实是在后台定义的)。
92+
93+
|
1494
1595
----------
1696
讨论
1797
----------
18-
todo...
98+
本小节会实实在在的测试你关于回调函数、生成器和控制流的知识。
99+
100+
首先,在需要使用到回调的代码中,关键点在于当前计算工作会挂起并在将来的某个时候重启(比如异步执行)。
101+
当计算重启时,回调函数被调用来继续处理结果。``apply_async()`` 函数演示了执行回调的实际逻辑,
102+
尽管实际情况中它可能会更加复杂(包括线程、进程、事件处理器等等)。
103+
104+
计算的暂停与重启思路跟生成器函数的执行模型不谋而合。
105+
具体来讲,``yield`` 操作会使一个生成器函数产生一个值并暂停。
106+
接下来调用生成器的 ``__next__()`` 或 ``send()`` 方法又会让它从暂停处继续执行。
107+
108+
根据这个思路,这一小节的核心就在 ``inline_async()`` 装饰器函数中了。
109+
关键点就是,装饰器会逐步遍历生成器函数的所有 ``yield`` 语句,每一次一个。
110+
为了这样做,刚开始的时候创建了一个 ``result`` 队列并向里面放入一个 ``None`` 值。
111+
然后开始一个循环操作,从队列中取出结果值并发送给生成器,它会持续到下一个 ``yield`` 语句,
112+
在这里一个 ``Async`` 的实例被接受到。然后循环开始检查函数和参数,并开始进行异步计算 ``apply_async()`` 。
113+
然而,这个计算有个最诡异部分是它并没有使用一个普通的回调函数,而是用队列的 ``put()`` 方法来回调。
114+
115+
这时候,是时候详细解释下到底发生了什么了。主循环立即返回顶部并在队列上执行 ``get()`` 操作。
116+
如果数据存在,它一定是 ``put()`` 回调存放的结果。如果没有数据,那么先暂停操作并等待结果的到来。
117+
这个具体怎样实现是由 ``apply_async()`` 函数来决定的。
118+
如果你不相信会有这么神奇的事情,你可以使用 ``multiprocessing`` 库来试一下,
119+
在单独的进程中执行异步计算操作,如下所示:
120+
121+
.. code-block:: python
122+
123+
if __name__ == '__main__':
124+
import multiprocessing
125+
pool = multiprocessing.Pool()
126+
apply_async = pool.apply_async
127+
128+
# Run the test function
129+
test()
130+
131+
实际上你会发现这个真的就是这样的,但是要解释清楚具体的控制流得需要点时间了。
132+
133+
将复杂的控制流隐藏到生成器函数背后的例子在标准库和第三方包中都能看到。
134+
比如,在``contextlib`` 中的 ``@contextmanager`` 装饰器使用了一个令人费解的技巧,
135+
通过一个 ``yield`` 语句将进入和离开上下文管理器粘合在一起。
136+
另外非常流行的 ``Twisted`` 包中也包含了非常类似的内联回调。

0 commit comments

Comments
 (0)