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

2

6

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?

Decarlo answered 30/3, 2012 at 7:52 Comment(0)
V
8

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.

Vowell answered 22/4, 2016 at 5:42 Comment(0)
K
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.

Kisner answered 30/3, 2012 at 8:35 Comment(2)
But how is it that just inspect.currentframe isn't supported, but inspect.trace and inspect.stack work fine? (That's what the docs imply.)Decarlo
And what alternative of inspect.currentframe() can be for ironpython?Womenfolk

© 2022 - 2024 — McMap. All rights reserved.