在 python 中检查堆栈中的局部变量

Examining local variables up the stack in python

我写了一个小函数,查找堆栈一层,看看里面是否有变量。但是我如何将这个函数变成一个在堆栈中一直向上查找直到它找到一个局部变量购买某个特定名称的函数?

import inspect
def variable_lookup(variable):
    parent_locals = inspect.currentframe().f_back.f_locals
    if variable in parent_locals.keys():
        return parent_locals[variable]

我想要的是循环直到它遍历所有堆栈,试图找到变量的东西。我怎样才能使用检查来做到这一点?有没有更简单的方法?

我从这个开始,但是 f_back 没有 return 框架对象所以我不知道从这里去哪里:

import inspect
def variable_lookup(variable):
previous_frame = inspect.currentframe().f_back
while True:
    print(variable in previous_frame.f_locals.keys())
    previous_frame = inspect.getframeinfo(previous_frame)

因此代码在 AttributeError: 'Traceback' object has no attribute 'f_locals'

时失败

有一个更高级别的函数可用:inspect.stack()。这为您提供了一个 FrameInfo() 对象的列表,其中有一个 frame 引用:

for frameinfo in inspect.stack(0):
    if variable in frameinfo.frame.f_locals:
        return frameinfo.frame.f_locals[variable]

我将源代码行数(context 参数)设置为零,加载源代码行只是为了检查局部变量没有意义。

stack()函数基本实现为:

return inspect.getouterframes(inspect.currentframe(), context)

getouterframes() 紧跟着 frame.f_back 引用,直到找到 None。所以你也可以用 while 循环来实现这个:

frame = inspect.currentframe()
while frame:
    if variable in frame.f_locals:
        return frame.f_locals[variable]
    frame = frame.f_back

这当然是更轻量级的,因为这避免了为堆栈中的所有帧创建 FrameInfo() 实例,避免了对所有帧的文件名进行内省,并且不需要访问所有链接的帧,如果变量发现早