Python:为什么没有堆栈帧`警告。警告`?

2024-09-24 12:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下代码:

#!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扩展函数根本没有堆栈帧吗?你知道吗


Tags: namepytesthomefoomydefbar