Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

sys._getframe() not behaving as expected

1 view
Skip to first unread message

Skip Montanaro

unread,
Dec 1, 2003, 4:05:01 PM12/1/03
to pytho...@python.org

sys._getframe() is acting peculiar. At least it doesn't seem to be doing
what I expect based upon a couple readings of its doc. Given this module
(call it 'gl'):

import sys

def printframes():
print "frame[-2]:", id(sys._getframe(-2))
print "frame[-1]:", id(sys._getframe(-1))
print "frame[0]:", id(sys._getframe(0))
print "frame[-2] globals:", id(sys._getframe(-2).f_globals)
print "frame[-1] globals:", id(sys._getframe(-1).f_globals)
print "frame[0] globals:", id(sys._getframe(0).f_globals)
print "my globals:", id(globals())

calling it like so from the interpreter prompt (CVS):

>>> import gl
>>> def f():
... gl.printframes()
...
>>> f()
frame[-2]: 3822448
frame[-1]: 3822448
frame[0]: 3822448
frame[-2] globals: 11889232
frame[-1] globals: 11889232
frame[0] globals: 11889232
my globals: 11889232
>>> id(globals())
3955136

The gl.printframes() function never prints the id of the interpreter's
globals(), nor does it ever print different frames. What am I missing? I
would like to get a handle on the globals for the frame from which
printframes() is called.

Skip

Tim Peters

unread,
Dec 1, 2003, 5:28:51 PM12/1/03
to pytho...@python.org
[Skip Montanaro]

> sys._getframe() is acting peculiar. At least it doesn't seem to be
> doing what I expect based upon a couple readings of its doc. Given
> this module (call it 'gl'):
>
> import sys
>
> def printframes():
> print "frame[-2]:", id(sys._getframe(-2))
> print "frame[-1]:", id(sys._getframe(-1))
> print "frame[0]:", id(sys._getframe(0))
> print "frame[-2] globals:", id(sys._getframe(-2).f_globals)
> print "frame[-1] globals:", id(sys._getframe(-1).f_globals)
> print "frame[0] globals:", id(sys._getframe(0).f_globals)
> print "my globals:", id(globals())
> ...

An argument < 0 is treated like 0. You want to pass 2 and 1, not -2 and -1.

Skip Montanaro

unread,
Dec 1, 2003, 11:14:13 PM12/1/03
to Tim Peters, pytho...@python.org

Tim> [Skip Montanaro]
>> sys._getframe() is acting peculiar.

Tim> An argument < 0 is treated like 0. You want to pass 2 and 1, not
Tim> -2 and -1.

Thanks. That is the final bit of mortar needed for a small brick wall. On
python-dev, Gerrit Holl suggested two new builtins: save() and load(), which
would allow a user to save a session and later restore it. The very
simpleminded implementation of that concept is available at

http://www.musi-cal.com/~skip/python/save_session.py

Skip


0 new messages