To understand and use python yield statement, you must know:
- yield often be used in a python function.
- yield can return a value, however, this value is a generator object, you can use obj.next() to get the real value.
- once a yield statement is executed, the status of this function will be saved and this function will be suspended to execute.
- When you call obj.next(), code in function will be executed from last yield or start of function to the next yeild.
We will write an example to help you understand.
Write a funcion contains yeild
def yieldtest(): print 'yield 1' yield 1 print 'yield 2' yield 2 print 'yield 3' yield 3 print 'end'
Get a generator object
m = yieldtest() print type(m) m
You will get:
<type 'generator'> >>> m <generator object yieldtest at 0x00000000069D8828>
Look at yieldtest() function, you will find 3 yield statements, which means you will call m.next() three times.
Print value in m
print m
The output is:
<generator object yieldtest at 0x00000000069D8828>
Which is not the real value of m, you should use m.next().
Call m.next() firstly, it will execute from beginning of function to yeild 1.
>>> print m.next()
The output is:
yield 1 1
Call m.next() secondly, it will execute from yield 1 to yield 2.
>>> print m.next()
The output is:
yield 2 2
Call m.next() thirdly, it will execute from yield 2 to yield 3.
>>> print m.next()
The output is:
yield 3 3
You may find the last sentence not be executed, you also can call m.next(), it will execute from yeild 3 to end of function yieldtest, however, it will report an error, because there is not return value.
Call m.next() fourthly
>>> print m.next()
The output is:
end Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
You will find the last sentence of yieldtest() is executed, but report an error.
How to void this error. we can use for in statement.
>>> for i in yieldtest(): ... print i
The output is:
yield 1 1 yield 2 2 yield 3 3 end
The last sentence of yieldtest() is executed, however, no error appears.