考虑以下代码:
#!python3
import warnings
import sys
def my_showwarning(*args, **kwargs):
frame = sys._getframe()
while frame is not None:
print('name:', frame.f_code.co_name, 'file:', frame.f_code.co_filename)
frame = frame.f_back
warnings.showwarning = my_showwarning
def foo():
bar()
def bar():
warnings.warn('Not good', UserWarning)
warnings.resetwarnings()
warnings.simplefilter('always')
foo()
输出为:
name: my_showwarning file: /home/nikratio/tmp/test.py
name: bar file: /home/nikratio/tmp/test.py
name: foo file: /home/nikratio/tmp/test.py
name: <module> file: /home/nikratio/tmp/test.py
为什么在bar()
和my_showwarnings
之间没有堆栈帧?看看cpython3.4.4中的实现,warnings.warn
应该调用warnings.warn_explicit
,它最终调用了showwarning
——所以在我看来,应该(至少)还有两个stackframe。你知道吗
这与CPython似乎默认使用C版本(_warnings
)有关吗?C扩展函数根本没有堆栈帧吗?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐