I l@ve RuBoard |
14.9 Introspecting the Call Stack with Older Versions of PythonCredit: Richard Philips, Christian Tismer 14.9.1 ProblemYou need to introspect information about a function on the call stack, but you also need to maintain compatibility with older Python versions. 14.9.2 SolutionFor 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 _getframe
Now you can use sys._getframe regardless of which version of Python you are using. 14.9.3 DiscussionThe 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. 14.9.4 See AlsoRecipe 14.8; documentation on the _getframe method of the sys module in the Library Reference. |
I l@ve RuBoard |