14.9 Introspecting the Call Stack with Older Versions of Python


Credit: Richard Philips, Christian Tismer

14.9.1 Problem

You 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 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 _getframe

Now you can use sys._getframe regardless of which version of Python you are using.

14.9.3 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.

14.9.4 See Also

Recipe 14.8; documentation on the _getframe method of the sys module in the Library Reference.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2005
Pages: 346

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net