pydocs
What is it?
- special type of function
- resumable function, variables aren’t thrown away when exiting the function
- any function containing yield keyword is a generator function
- vs a normal function
- normal function - compute and return value
- generator - returns an iterator that returns a stream of values
Yield vs return
- on reaching a yield, the generator’s state of execution is suspended and local vars preserved
- when calling
__next__() the function will resume executing
def generate_ints(N):
for i in range(N):
yield i
gen = generate_ints(3)
next(gen)
# displays 0
next(gen)
# displays 1