Wednesday, June 11, 2014

Prying Open a Generator

A Python generator is very like a function but is characterized by the keyword yield, and preserves state between calls.

For example you might have a generator that keeps spitting back a successive digits of Pi, but to do that, it needs to keep track of internal values between called to pi_digits.__next__() or whatever.

Do we have a way to take a generator that's already been advanced through several yields, and study the internal values of its state variables?  Yes.

Steve Holden wrote some code like the following to show me how it's done:

The output is:

... the current values of i, and n, respectively.

Using a FrameType object, you get to act like a debugger and get into the current state. This technique applies to more than just generators, but I think generators are a good example of something the guts of which you might want to peek into.