1

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

thogra
  • 315
  • 1
  • 10
  • please show the part in `b.py`where you write `current_mse` - your code is wirking fine for me, so far - nothing unexpected – Skandix Feb 14 '18 at 14:50

1 Answers1

0

A module creates a namespace, code inside b.py won't see a.py vars despite being imported by a.py. If they were in the same module and you were reading vars only, just use their names and they will be picked. For writing vars, you need to declare them global.

To get to all of the globals, these links can be of help (essentially you have to import them)

python-global-dict-across-different-file-script

get-global-variables-from-file-as-dict

progmatico
  • 4,714
  • 1
  • 16
  • 27