Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Stumbled upon this question while looking for the answer myself. The availability of inspect.currentframe is tied to sys._getframe:

defcurrentframe():
    """Return the frame of the caller or None if this is not possible."""return sys._getframe(1) ifhasattr(sys, "_getframe") elseNone

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.

Solution 2:

The other implementations the docs refer to are Jython and IronPython. These are Python language implementations that run in a different VM (JVM and CLR) and don't have such a stack frame. I think IronPython has later added some support for that, however.

Post a Comment for "Inspect.currentframe() May Not Work Under Some Implementations?"