twosnac twosnac - 1 year ago 64
Python Question

How do I get access to all current stack frames' f_globals attribute

I'm trying get all of the current stack frames and do some inspection on each frames f_globals attribute for each frame. This is very similar to how the unittest module does it except that in my case, an exception has not been thrown. traceback.extract_stack() does not give access to this but the frame in sys.exc_info() does when an exception is thrown.


Just use the "stack" function from the inspect module:

>>> import inspect
>>> for frame_tuple in inspect.stack():
...    print frame_tuple[0].f_globals.keys()
['frame_tuple', '__builtins__', 'inspect', '__package__', '__name__', 'readline', 'rlcompleter', '__doc__']

The call to it yields a list, where each element is a tuple consisting of the running frame and some extra information on that frame.

This function is slow, though, to be used in actual runniong code for anything other than setting things up, or debugging. If you need to inspect the stack fro some runtime operation - like fetching variable values, or other introspection-based code, do use inspect.currentframe() to get the currentframe, and the .f_back property on each frame for links to the previous frames - this is fast enough.

You should not use "sys._getframe", since, as the underscore at the start of the name indicates, it is not intended for public use.