Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 622
twosnac Avatar asked Jan 26 '12 22:01

twosnac


1 Answers

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

>>> import inspect
>>> inspect.stack()
[(<frame object at 0x02467FE0>, '<stdin>', 1, '<module>', None, None)]

This call yields a list, where each element is a tuple consisting of the running frame and extra information on that frame (according to Python docs):

[frame, filename, line number, function name, frame sources, current line index in sources]

To inspect f_globals on each frame object:

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

"stack" function is slow, though, to be used in actual running code for anything other than setting things up, or debugging. If you need to inspect the stack for 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.

like image 196
jsbueno Avatar answered Sep 28 '22 08:09

jsbueno