Python 如何访问不同作用域的locals()dict?

Python 如何访问不同作用域的locals()dict?,python,metaprogramming,Python,Metaprogramming,我正在编写一个调试器,需要访问以前称为frame的局部变量 例如,我有这样一个代码: def foo(): ... result = bar(args) # bar is some function locals_of_bar = ...#get the locals() dict of the frame in which `bar` was called 编辑:为了更清楚,我更新了问题。你能做的最好的事情是: def foo(): print bar_loc

我正在编写一个调试器,需要访问以前称为frame的局部变量

例如,我有这样一个代码:

def foo():
    ...
    result = bar(args) # bar is some function 
    locals_of_bar = ...#get the locals() dict of the frame in which `bar` was called

编辑:为了更清楚,我更新了问题。

你能做的最好的事情是:

def foo():
   print bar_locals()

def bar_locals():
   a=1
   b=2
   return locals()
或者:

您可以执行以下操作:

_方法的局部数_={}

def bar(): #执行功能 方法的全局局部性 局部变量\u of_方法['bar':locals()] #返回


执行
bar()
后,在方法的
locals\u中有局部变量

函数没有局部变量。堆栈帧(具体函数调用)有。您的问题在技术上似乎不正确,因为它适用于堆栈调用,并且在调用和从方法返回时会创建和销毁局部变量。我希望动态执行此操作,因此我不希望编辑该函数,以便为我调试的每个函数插入
return locals()
。我想知道是否有可能从以前执行的帧中获取数据。请理解,
func
被加载到堆栈中,并使用其
局部变量执行,然后卸载,因此基本上它卸载了仅用于
func
的所有内容,因此去掉了局部变量。您已经说过,您必须将它们导出到某个地方,以便稍后或动态访问它们。您是对的,但是可以从回溯中提取帧的
局部变量。Werkzeug这样做-。我想我现在只能靠追踪来勉强度日了。