问题描述
根据文档:
inspect.currentframe()
返回调用者堆栈的框架对象框架.
Return the frame object for the caller’s stack frame.
CPython 实现细节:此函数依赖于 Python 堆栈解释器中的框架支持,不保证存在于Python的所有实现.如果在没有的实现中运行Python栈帧支持这个函数返回None.
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.
为什么只有这个函数被标记为依赖于实现"?如果这个功能不起作用,是不是类似的功能,如inspect.trace
、inspect.stack
等也无法使用?
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?
推荐答案
在自己寻找答案时偶然发现了这个问题.inspect.currentframe
的可用性与 sys._getframe
相关:
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
因此,该限制适用于所有其他也使用 sys._getframe
的函数.对于 inspect
,这只是 inspect.stack
.
The restriction thus applies to all other functions also using sys._getframe
. For inspect
, this is only inspect.stack
.
相比之下,inspect.trace
使用 sys.exc_info
.这是异常处理方案的一个组成部分,并且应该始终可用.所有其他相关功能,例如getframeinfo
,已经依赖有一个框架.它们的适用性取决于您是要检查异常还是要调用回溯.
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.
请注意,我的本地默认 jython 确实支持 sys._getframe
.如果使用 -X:Frames
运行,ipy 可以工作.
Note that my local, default jython does support sys._getframe
. ipy works if run with -X:Frames
.
这篇关于inspect.currentframe() 在某些实现下可能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!