Why are python generator frames' (gi_frame) f_back attribute always none?

1.7k views Asked by At

The title is pretty self-explanatory. I'm doing something like:

gen = obj #some generator instance running
frame = obj.gi_frame
prevframe = frame.f_back

But I always get None for prevframe. Why is this the case. Also, is there some workaround for this?

CONTEXT: I'm trying to write a simple call stack method to determine what called a particular function. I'm using twisted manhole and telnetting into a running process, where I then execute these commands but I can't seem to access the previous frames.

1

There are 1 answers

0
Audrey Dutcher On

To the best of my knowledge, this is both intentional and cannot be worked around. The code in cpython responsible for it is here, which indicates that the reference to the previous frame is broken as soon as the generator yields (or excepts out) in order to prevent issues with reference counting. It also appears that the intended behavior is that the generator's previous frame is swapped out every time it's entered, so while it's not running, the notion of "the parent frame" doesn't make much sense.

The correct way to do this, at least in the post-mortem context, is to use traceback objects, which have their frame lists linked in the reverse order, tb_next instead of f_back.