A function where the
Calling the function returns a generator object. This objects saves it's internal state.
The generator object is also an
This is where 'magic' comes in-place. Calling
object, executes the code until the first
The Fibonacci example has a loop, where the
yield
keyword is used, is a generator.Calling the function returns a generator object. This objects saves it's internal state.
The generator object is also an
iterator
.This is where 'magic' comes in-place. Calling
next()
on a generatorobject, executes the code until the first
yield
has been reached.def gen1(): yield 1337 g = gen1() # no code execution next(g) # gives you 1337 next(g) # Raises StopIterationSince Python 3.4 you can and should use the
return
statement inside a generator to stop the iteration. It's better then raise StopIteration
, which makes trouble with newer version of Python.The Fibonacci example has a loop, where the
yield
keyword is hit more than one time. This is the cause, why it behaves like a loop.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!