## Friday, August 25, 2017

### python generator and yield

Generators are best for calculating large sets of results (particularly calculations involving loops themselves) where you don’t want to allocate the memory for all results at the same time.

To understand generator and yield, we can debug the code below.

```
def fibon(n):
print('testing generator...')
a = b = 1
for i in range(n):
yield a
a, b = b, a + b

if __name__ == '__main__':
for x in fibon(10):
print(x)
# do something with x which consumes a lot of resources
```

put break point at line 5,6 and 10
1. when the code is executed, line 9, it calls fibon(10) to get x
2. the fibon function is executed to line 5, yield a, it suspends the process of fibon and return to the main process, x gets the value of a.
3. Then line 10, print(x), we can have code here which consumes system resources here.
4. Once it is done, it goes back to line 9, for x in fibon(10), ask for next value from fibon function
5. It goes to line 6, the place where it is suspended, run the calculation, continue the iteration to line 4, 5 yield again, it will pop the calculated value to the main process line 10 again.
Send method
to send the value into the function
```
def echo(value=None):
while True:
value = (yield value)
print("the value is", value)
value += 1

if __name__ == '__main__':
g = echo(100)
valueFromYeild = next(g)
print("value From Yield", valueFromYeild)
sendReturn = g.send(27)
print("sendReturn", sendReturn)

print("send in 5")
sendReturn = g.send(5)
print("sendReturn", sendReturn)
```

http://book.pythontips.com/en/latest/generators.html
http://kissg.me/2016/04/09/python-generator-yield/