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 _getframe

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

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.