pythonpython-3.xstacklanguage-implementation

inspect.currentframe() may not work under some implementations?


According to the docs:

inspect.currentframe()

Return the frame object for the caller’s stack frame.

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

How is it that only this function is marked as "implementation-dependent"? If this function doesn't work, wouldn't similar functions, such as inspect.trace, inspect.stack, etc. also be unavailable?

Also, what does "stack frame support" mean, and why would it ever be absent?


Solution

  • The availability of inspect.currentframe is tied to sys._getframe:

    def currentframe():
        """Return the frame of the caller or None if this is not possible."""
        return sys._getframe(1) if hasattr(sys, "_getframe") else None
    

    The restriction thus applies to all other functions also using sys._getframe. For inspect, this is only inspect.stack.

    In contrast, inspect.trace uses sys.exc_info. This is an integral part of exception handling schemes, and should always be available. All other related function, e.g. getframeinfo, already rely on there being a frame. Their applicability depends on whether you want to inspect an exception or call traceback.

    Note that my local, default jython does support sys._getframe. ipy works if run with -X:Frames.