Tuesday, April 21, 2020

Python Generator


Have you ever  think through how to build an function that generate infinite series ?
You might be  thinking why can't we use an infinite loop! the problem is you can't come of the loop and again resume from the position/state where you stopped .

But generators helps in this case, they are just like functions but the difference is they have yield keyword in the definition which is like a return wrapped with generator-iterator object

"When you call either a function or a generator, a stackframe is created. It has the local variables
(including the arguments passed into the function),a code pointer to the active opcode, and a stack for pending try-blocks,with-blocks, or loops.

In a regular function, execution begins immediately.When return is encountered, the final result is kept and the stackframe is freed along with everything it referenced.

In a generator function, the stackframe is wrapped in a generator-iterator object and returned immediately. The code in the generator function only runs when called by next(g) or g.send(v). Execution is suspended when yield is encountered. "



Python generator infinite sequence example

Python generator things to be known ( exhausted generator )


No comments: