Skip to content

Commit aaab8eb

Browse files
committed
add generator
1 parent cb3f3e2 commit aaab8eb

1 file changed

Lines changed: 236 additions & 1 deletion

File tree

‎Advanced-Features/generator.md‎

Lines changed: 236 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,237 @@
1-
# 生成器
1+
生成器
2+
====
3+
4+
生成器(generator)也是一种迭代器,在每次迭代时返回一个值,直到抛出 `StopIteration` 异常。它有两种构造方式:
5+
6+
- 生成器表达式
7+
8+
和列表推导式的定义类似,生成器表达式使用 `()` 而不是 `[]`,比如:
9+
10+
```
11+
numbers = (x for x in range(5)) # 注意是(),而不是[]
12+
for num in numbers:
13+
print num
14+
```
15+
16+
- 生成器函数
17+
18+
含有 `yield` 关键字的函数,调用该函数时会返回一个生成器。
19+
20+
本文主要讲**生成器函数**。
21+
22+
# 生成器函数
23+
24+
先来看一个简单的例子:
25+
26+
```python
27+
>>> def generator_function():
28+
... print 'hello 1'
29+
... yield 1
30+
... print 'hello 2'
31+
... yield 2
32+
... print 'hello 3'
33+
>>>
34+
>>> g = generator_function() # 函数没有立即执行,而是返回了一个生成器,当然也是一个迭代器
35+
>>> g.next() # 当使用 next() 方法,或使用 next(g) 的时候开始执行,遇到 yield 暂停
36+
hello 1
37+
1
38+
>>> g.next() # 从原来暂停的地方继续执行
39+
hello 2
40+
2
41+
>>> g.next() # 从原来暂停的地方继续执行,没有 yield,抛出异常
42+
hello 3
43+
Traceback (most recent call last):
44+
File "<stdin>", line 1, in <module>
45+
StopIteration
46+
```
47+
48+
可以看到,上面的函数没有使用 `return` 语句返回值,而是使用了 `yield`『生出』一个值。一个带有 `yield` 的函数就是一个生成器函数,当我们使用 `yield` 时,它帮我们自动创建了 `__iter__()` 和 `next()` 方法,而且在没有数据时,也会抛出 `StopIteration` 异常,也就是我们不费吹灰之力就获得了一个迭代器,非常简洁和高效。
49+
50+
带有 `yield` 的函数执行过程比较特别:
51+
52+
- 调用该函数的时候不会立即执行代码,而是返回了一个生成器对象;
53+
- 当使用 `next()` (在 for 循环中会自动调用 `next()`) 作用于返回的生成器对象时,函数开始执行,在遇到 `yield` 的时候会『暂停』,并返回当前的迭代值;
54+
- 当再次使用 `next()` 的时候,函数会从原来『暂停』的地方继续执行,直到遇到 `yield` 语句,如果没有 `yield` 语句,则抛出异常;
55+
56+
整个过程看起来就是不断地 `执行->中断->执行->中断` 的过程。一开始,调用生成器函数的时候,函数不会立即执行,而是返回一个生成器对象;然后,当我们使用 `next()` 作用于它的时候,它开始执行,遇到 `yield` 语句的时候,执行被中断,并返回当前的迭代值,要注意的是,此刻会记住中断的位置和所有的变量值,也就是执行时的上下文环境被保留起来;当再次使用 `next()` 的时候,从原来中断的地方继续执行,直至遇到 `yield`,如果没有 `yield`,则抛出异常。
57+
58+
**简而言之,就是 `next` 使函数执行,`yield` 使函数暂停。**
59+
60+
# 例子
61+
62+
看一个 Fibonacci 数列的例子,如果使用自定义迭代器的方法,是这样的:
63+
64+
```python
65+
>>> class Fib(object):
66+
... def __init__(self):
67+
... self.a, self.b = 0, 1
68+
... def __iter__(self):
69+
... return self
70+
... def next(self):
71+
... self.a, self.b = self.b, self.a + self.b
72+
... return self.a
73+
...
74+
>>> f = Fib()
75+
>>> for item in f:
76+
... if item > 10:
77+
... break
78+
... print item
79+
...
80+
1
81+
1
82+
2
83+
3
84+
5
85+
8
86+
```
87+
88+
而使用生成器的方法,是这样的:
89+
90+
```python
91+
>>> def fib():
92+
... a, b = 0, 1
93+
... while True:
94+
... a, b = b, a + b
95+
... yield a
96+
...
97+
>>> f = fib()
98+
>>> for item in f:
99+
... if item > 10:
100+
... break
101+
... print item
102+
...
103+
1
104+
1
105+
2
106+
3
107+
5
108+
8
109+
```
110+
111+
可以看到,使用生成器的方法非常简洁,不用自定义 `__iter__()` 和 `next()` 方法。
112+
113+
另外,在处理大文件的时候,我们可能无法一次性将其载入内存,这时可以通过构造固定长度的缓冲区,来不断读取文件内容。有了 `yield`,我们就不用自己实现读文件的迭代器了,比如下面的实现:
114+
115+
```python
116+
def read_in_chunks(file_object, chunk_size=1024):
117+
"""Lazy function (generator) to read a file piece by piece.
118+
Default chunk size: 1k."""
119+
while True:
120+
data = file_object.read(chunk_size)
121+
if not data:
122+
break
123+
yield data
124+
125+
f = open('really_big_file.dat')
126+
for piece in read_in_chunks(f):
127+
process_data(piece)
128+
```
129+
130+
# 进阶使用
131+
132+
我们除了能对生成器进行迭代使它返回值外,还能:
133+
134+
- 使用 `send()` 方法给它发送消息;
135+
- 使用 `thow()` 方法给它发送异常;
136+
- 使用 `close()` 方法关闭生成器;
137+
138+
## send() 方法
139+
140+
看一个简单的例子:
141+
142+
```
143+
>>> def generator_function():
144+
... value1 = yield 0
145+
... print 'value1 is ', value1
146+
... value2 = yield 1
147+
... print 'value2 is ', value2
148+
... value3 = yield 2
149+
... print 'value3 is ', value3
150+
...
151+
>>> g = generator_function()
152+
>>> g.next() # 调用 next() 方法开始执行,返回 0
153+
0
154+
>>> g.send(2)
155+
value1 is 2
156+
1
157+
>>> g.send(3)
158+
value2 is 3
159+
2
160+
>>> g.send(4)
161+
value3 is 4
162+
Traceback (most recent call last):
163+
File "<stdin>", line 1, in <module>
164+
StopIteration
165+
```
166+
167+
在上面的代码中,我们先调用 `next()` 方法,使函数开始执行,代码执行到 `yield 0` 的时候暂停,返回了 0;接着,我们执行了 `send()` 方法,它会恢复生成器的运行,并将发送的值赋给上次中断时 yield 表达式的执行结果,也就是 value1,这时控制台打印出 value1 的值,并继续执行,直到遇到 yield 后暂停,此时返回 1;类似地,再次执行 `send()` 方法,将值赋给 value2。
168+
169+
简单地说,`send()` 方法就是 `next()` 的功能,加上传值给 `yield`。
170+
171+
## throw() 方法
172+
173+
除了可以给生成器传值,我们还可以给它传异常,比如:
174+
175+
```python
176+
>>> def generator_function():
177+
... try:
178+
... yield 'Normal'
179+
... except ValueError:
180+
... yield 'Error'
181+
... finally:
182+
... print 'Finally'
183+
...
184+
>>> g = generator_function()
185+
>>> g.next()
186+
'Normal'
187+
>>> g.throw(ValueError)
188+
'Error'
189+
>>> g.next()
190+
Finally
191+
Traceback (most recent call last):
192+
File "<stdin>", line 1, in <module>
193+
StopIteration
194+
```
195+
196+
可以看到,`throw()` 方法向生成器函数传递了 `ValueError` 异常,此时代码进入 except ValueError 语句,遇到 yield 'Error',暂停并返回 Error 字符串。
197+
198+
简单的说,`throw()` 就是 `next()` 的功能,加上传异常给 `yield`。
199+
200+
## close() 方法
201+
202+
我们可以使用 `close()` 方法来关闭一个生成器。生成器被关闭后,再次调用 next() 方法,不管能否遇到 yield 关键字,都会抛出 StopIteration 异常,比如:
203+
204+
```python
205+
>>> def generator_function():
206+
... yield 1
207+
... yield 2
208+
... yield 3
209+
...
210+
>>> g = generator_function()
211+
>>>
212+
>>> g.next()
213+
1
214+
>>> g.close() # 关闭生成器
215+
>>> g.next()
216+
Traceback (most recent call last):
217+
File "<stdin>", line 1, in <module>
218+
StopIteration
219+
```
220+
221+
# 小结
222+
223+
- yield 把函数变成了一个生成器。
224+
- 生成器函数的执行过程看起来就是不断地 `执行->中断->执行->中断` 的过程。
225+
- 一开始,调用生成器函数的时候,函数不会立即执行,而是返回一个生成器对象;
226+
- 然后,当我们使用 `next()` 作用于它的时候,它开始执行,遇到 `yield` 语句的时候,执行被中断,并返回当前的迭代值,要注意的是,此刻会记住中断的位置和所有的数据,也就是执行时的上下文环境被保留起来;
227+
- 当再次使用 `next()` 的时候,从原来中断的地方继续执行,直至遇到 `yield`,如果没有 `yield`,则抛出异常。
228+
229+
230+
# 参考资料
231+
232+
- [Python yield 使用浅析](https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/)
233+
- [谈谈Python的生成器 – 思诚之道](http://www.bjhee.com/python-yield.html)
234+
- [Function vs Generator in Python](https://code-maven.com/function-vs-generator-in-python)
235+
- [Lazy Method for Reading Big File in Python? - Stack Overflow](http://stackoverflow.com/questions/519633/lazy-method-for-reading-big-file-in-python)
236+
2237

0 commit comments

Comments
 (0)