【问题标题】:How do I access the locals() dict of a different scope?如何访问不同范围的 locals() 字典?
【发布时间】:2012-03-04 05:24:45
【问题描述】:

我正在编写一个调试器,我需要访问以前调用的框架的局部变量

例如,我有这样的代码:

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

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

【问题讨论】:

  • 函数没有本地人。栈帧(具体函数调用)有。
  • 您的问题在技术上似乎不正确,因为它适用于堆栈调用,并且在调用和从方法返回时创建和销毁局部变量。

标签: python metaprogramming


【解决方案1】:

你能做的最好的就是:

def foo():
   print bar_locals()

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

或者:

你可以这样做:

locals_of_methods = {}

定义栏(): # 执行功能 全局 locals_of_methods locals_of_methods['bar':locals()] #返回

执行bar()后,你将拥有locals_of_methods中的本地人

【讨论】:

  • 我想动态地做,所以我不想编辑函数来为我调试的每个函数插入一个return locals()。我想知道是否可以从以前执行的帧中获取数据。
  • 请理解 func 被加载到堆栈并使用它的 locals 执行然后它被卸载,所以基本上它卸载了所有只是为了 func 的东西,因此摆脱了当地人。话虽如此,您必须将它们导出到某个地方以便以后或即时访问它们。
  • 你是对的,但是可以从回溯中提取帧的locals。 Werkzeug 这样做 - github.com/mitsuhiko/werkzeug/blob/… 。我想我现在只能使用回溯。
猜你喜欢
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2017-05-20
相关资源
最近更新 更多