inspect.getouterframes()函数返回的元组中的'index'元素是什么?

4 投票
2 回答
769 浏览
提问于 2025-04-17 18:14

我在Python中对inspect.getouterframes做了个help,结果得到了以下内容:

getouterframes(frame, **context**=1)
Get a list of records for a frame and all higher (calling) frames.

Each record contains a frame object, filename, line number, function
name, a list of lines of context, and **index within the context**.

这些“context”和“index”是什么意思呢?

2 个回答

0

FrameInfo中的index元素是指在FrameInfo.context中,给定行的索引位置。

根据文档的说明:

这个元组包含了帧对象、文件名、当前行的行号、函数名、源代码的上下文行列表,以及在这个列表中当前行的索引。

1

这是为了给当前这一行代码添加一些周围代码的背景信息。简单的例子:

import sys
import inspect

def f():
    # prev
    return sys._getframe()
    # next

# prev
framelist = inspect.getouterframes(f(), 3)
# next

for frame in framelist:
    print frame[3], "context:\n"
    for i, line in enumerate(frame[-2]):
        print line.rstrip(),
        if i == frame[-1]:
            print ' *** index ***'
        else:
            print
    print

输出结果:

f context:

    # prev
    return sys._getframe()  *** index ***
    # next

<module> context:

# prev
framelist = inspect.getouterframes(f(), 3)  *** index ***
# next

撰写回答