在某些实现下,inspect.currentframe() 可能不起作用? [英] inspect.currentframe() may not work under some implementations?

查看:25
本文介绍了在某些实现下,inspect.currentframe() 可能不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档:

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.traceinspect.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() 可能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆