Introspecting the Call Stack with Older Versions of Python
Credit: Richard Philips, Christian Tismer
Problem
You need to introspect information about a function on the call stack, but you also need to maintain compatibility with older Python versions.
Solution
For debugging purposes, you often want to know where a function was
called from or other call-stack information. The
_getframe
function helps. Just ensure that the following code is executed
during your program’s startup:
import sys
try: sys._getframe
except AttributeError: # We must be using some old version of Python, so:
def _getframe(level=0):
try: 1/0
except: tb = sys.exc_info( )[-1]
frame = tb.tb_frame
while level >= 0:
frame = frame.f_back
level = level - 1
return frame
sys._getframe = _getframe
del _getframeNow you can use sys._getframe regardless of which
version of Python you are using.
Discussion
The
sys._getframe function, which is
invaluable for introspection anywhere in the call stack, was
introduced in Python 2.1. If you need to introspect the call stack
but maintain compatibility with older Python versions, this recipe
shows how to simulate sys._getframe and inject the
function’s implementation in the
sys module, so that you can use it freely
regardless of which version of Python you use.
See Also
Recipe 14.8; documentation on the
_getframe method of the sys
module in the Library Reference.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access