You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调试时使用inspect.stack()无法获取函数名的问题

问题:inspect.stack()[0][4]无法输出函数名的解决办法

问题代码

import inspect
def fn1(x):
 print(1*x)
 print(inspect.stack()[0][4]) #print fn1

def fn2(x):
 print(2*x*x)
 print(inspect.stack()[0][4]) #print fn2

def fn3(x):
 print(3*x*x*x)
 print(inspect.stack()[0][4]) #print fn3

class printFuncName():
 def __init__(fn):
    self.fn = fn
    self.fn(12)

if __name__ == '__main__':
   funcs = [fn1, fn2, fn3]    
   for ii in funcs:
     printFuncName(ii)

问题描述

运行上述代码时,print(inspect.stack()[0][4])仅输出空字符串'',无法得到预期的函数名'fn1', 'fn2', 'fn3'。

解决方案

inspect.stack()[0][4]对应的是当前帧的源代码行内容,并非函数名字段,因此会输出空值。要获取函数名,有两种可靠方式:

方式1:调用inspect.stack()的函数名字段

inspect.stack()返回的FrameInfo列表中,每个元素的第3个索引([0][3])对应当前函数名称:

print(inspect.stack()[0][3])

方式2:从当前帧的代码对象直接获取

通过inspect.currentframe()获取当前执行帧,再访问f_code.co_name属性:

print(inspect.currentframe().f_code.co_name)

修正后的完整代码

import inspect
def fn1(x):
 print(1*x)
 print(inspect.currentframe().f_code.co_name) # 输出fn1

def fn2(x):
 print(2*x*x)
 print(inspect.currentframe().f_code.co_name) # 输出fn2

def fn3(x):
 print(3*x*x*x)
 print(inspect.currentframe().f_code.co_name) # 输出fn3

class printFuncName():
 def __init__(self, fn):  # 修复原代码参数错误:需传入self作为第一个参数
    self.fn = fn
    self.fn(12)

if __name__ == '__main__':
   funcs = [fn1, fn2, fn3]    
   for ii in funcs:
     printFuncName(ii)

内容的提问来源于stack exchange,提问作者Zanam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:30:36