问题
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?
回答1:
Stumbled upon this question while looking for the answer myself. 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
.
回答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.
来源:https://stackoverflow.com/questions/9938980/inspect-currentframe-may-not-work-under-some-implementations