inspect.stack() and frame

Alf P. Steinbach alfps at start.no
Thu Mar 11 18:22:02 EST 2010


* Félix-Antoine Fortin:
> Given this code :
> # Experience with frame
> import sys
> import inspect
> 
> def foo():
>     stack = inspect.stack()
>     print "foo frame : " + str(hex(id(sys._getframe())))

hex returns a string. applying str is therefore redundant.


> def foo2():
>     inspect.stack()
>     print "foo2 frame : " + str(hex(id(sys._getframe())))
> 
> def bar():
>     print "bar frame : " + str(hex(id(sys._getframe())))
> 
> foo()
> foo()
> 
> foo2()
> foo2()
> 
> bar()
> bar()
> 
> Output example :
> foo frame : 0x84d2c0
> foo frame : 0x844bf0
> foo2 frame : 0x898c90
> foo2 frame : 0x898c90
> bar frame : 0x898f70
> bar frame : 0x898f70
> 
> Why are the ids (address) of the frame for each foo call not the same?

You're dealing with Python objects. You're not dealing with the computer's 
machine stack. Whether you get the same id for two objects whose lifetimes don't 
overlap depends on the implementation's memory and id allocation strategy.


> Or why the call to "stack = inspect.stack()" change the address of the
> frame?

Does it?


Cheers,

- Alf



More information about the Python-list mailing list