【发布时间】:2018-07-25 03:36:12
【问题描述】:
当我在重构我的代码时,我像这样重写了一个代码 sn-p
#Some initialization...
for iter in range(max_loops):
#Do some stuff
#....
if iter % print_modulo == 0:
print("Iteration %d, Energy: %f, ..." % (iter, current_mse))
分成两个不同的部分,一个在一个类中,另一个在调用那个类。由于我有多个回调,我决定获取调用者的全局变量以获得快速原型
a.py
import b
import inspect
def outputCallback(iter):
if iter % print_modulo == 0:
context = inspect.stack()[1][0].f_globals
print("Iteration %d, Energy: %f, ..." % (iter,
context['current_mse'])
#Some initialization...
opt = b.opt()
opt.run(iterations, [outputCallback])
b.py
class opt:
def run(self, max_loops, iteration_callbacks=[]):
for iter in range(max_loops):
#Do some stuff
#...
for callback in iteration_callbacks:
callback(iter)
但代码因关键错误而崩溃。我使用 PyCharm 调试到该行并尝试了不同的堆栈,但据我所知,inspect.stack()[0][0].f_globals 从 a.py 返回全局变量,但调试器的调用堆栈告诉我上面的堆栈帧 outputCallback是run(如预期的那样)。
我还尝试通过callback(iter, globals()) 在 b 中调用我的回调并将 outputCallback 更改为 def outputCallback(iter, context):,但仍然遇到相同的错误。
我做错了什么?如何简单地捕获 opt.run 中所有定义的变量并将它们转发给我的回调?
提前致谢
【问题讨论】:
-
请在
b.py中显示你写current_mse的部分 - 到目前为止,你的代码对我来说很好 - 没什么意外
标签: python python-3.x dictionary scope globals