while I was restructuring my code, I rewrote a code snippet like this
#Some initialization...
for iter in range(max_loops):
#Do some stuff
#....
if iter % print_modulo == 0:
print("Iteration %d, Energy: %f, ..." % (iter, current_mse))
into two different parts, one is in a class and another is calling that class. Since I'm having multiple callbacks, I decided to fetch the globals variable of the caller for a quick prototype
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)
But the code crashes with a key error. I debugged into the line with PyCharm and tried the different stacks, but as far as I can tell, inspect.stack()[0][0].f_globals
returns the globals from a.py, but the call-stack from the debugger tells me that the stack frame above outputCallback
is run
(as expected).
I also tried to call my callback in b via callback(iter, globals())
and changed outputCallback to def outputCallback(iter, context):
, but still got the same error.
What am I doing wrong? How can I simply capture all defined variables inside opt.run and forward them to my callbacks?
Thanks in advance