inspect.getargvalues() 抛出异常“AttributeError: 'tuple' 对象没有属性 'f_code'”

Tim*_*imB 2 python introspection

我正在尝试使用 Python 的inspect模块(在 Python 2 中)来显示有关调用当前函数的函数的信息,包括其参数。

这是一个简单的测试程序:

import inspect

def caller_args():
    frame = inspect.currentframe()
    outer_frames = inspect.getouterframes(frame)
    caller_frame = outer_frames[1]
    return inspect.getargvalues(caller_frame)

def fun_a(arg1):
    print caller_args()

def fun_b():
    fun_a('foo')

if __name__ == '__main__':
    fun_b()
Run Code Online (Sandbox Code Playgroud)

当我运行它时会发生这种情况:

$ python getargvalues_test.py
Traceback (most recent call last):
  File "getargvalues_test.py", line 16, in <module>
    fun_b()
  File "getargvalues_test.py", line 13, in fun_b
    fun_a('foo')
  File "getargvalues_test.py", line 10, in fun_a
    print caller_args()
  File "getargvalues_test.py", line 7, in caller_args
    return inspect.getargvalues(caller_frame)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 829, in getargvalues
    args, varargs, varkw = getargs(frame.f_code)
AttributeError: 'tuple' object has no attribute 'f_code'
Run Code Online (Sandbox Code Playgroud)

我用谷歌搜索了那个 AttributeError 异常,但没有运气。我究竟做错了什么?

(我已经找到了这个问题,所以我在这里问和回答这个问题,所以将来遇到这个问题的任何人都可以在这里找到答案。)

Tim*_*imB 5

这个类似的问题帮助我发现了这个问题。

Python文档inspect模块都提到“帧记录”和“帧对象”,并解释了区别。

  • inspect.currentframe()返回一个框架对象,但
  • inspect.getouterframes()返回帧记录列表。

上面代码中的错误是没有从调用函数的帧记录中提取帧对象,inspect.getouterframes()而是传递了帧记录而不是帧对象。(请注意,inspect.getouterframes()它不会检查其参数是否为框架对象。)

这是 的固定定义caller_args()(更改了对 的分配caller_frame):

def caller_args():
    frame = inspect.currentframe()
    outer_frames = inspect.getouterframes(frame)
    caller_frame = outer_frames[1][0]
    return inspect.getargvalues(caller_frame)
Run Code Online (Sandbox Code Playgroud)

根据需要运行:

$ python getargvalues_test_fixed.py
ArgInfo(args=['arg1'], varargs=None, keywords=None, locals={'arg1': 'foo'})
Run Code Online (Sandbox Code Playgroud)