2

worker file: vir.py

def calcCycleOffset():
    global cycleOffset, uc, cs

    cycleOffset = uc - cs
    return cycleOffset


def vir_main():
    calcCycleOffset()


vir_main()
#calcCycleOffset()


print( "vir.py: cycleOffset: ", cycleOffset )

executor file: exec.py

filename = "./vir.py"
vir_globals = { "uc": 42, "cs": 12, "cycleOffset": -1 }

with open(filename, "rb") as source_file:
    code = compile(source_file.read(), filename, "exec")

exec(code, vir_globals, {} )

print( 'exec: globals.cycleOffset', vir_globals['cycleOffset'] )

this pattern fails with:

Traceback (most recent call last):
  File "exec.py", line 7, in <module>
    exec(code, vir_globals, {} )
  File "./vir.py", line 12, in <module>
    vir_main()
  File "./vir.py", line 9, in vir_main
    calcCycleOffset()
NameError: name 'calcCycleOffset' is not defined

however, the function calcCycleOffset() is known to python. if you switch commenting in vir.py from:

vir_main()
#calcCycleOffset()

to:

#vir_main()
calcCycleOffset()

then the function is called OK.

I would like to be able to nest functions within function in the vir.py file and still be able to execute it dynamically...

HELP !

thanks

jossefaz
  • 3,312
  • 4
  • 17
  • 40
yonib
  • 33
  • 4

1 Answers1

1

As explained here in official documentation about the locals object: https://docs.python.org/3.8/library/functions.html#locals

Note : The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

And You passed here an empty object as locals.

In your executor files Please change your code to :

filename = "./vir.py"
vir_globals = { "uc": 42, "cs": 12, "cycleOffset": -1 }

with open(filename, "rb") as source_file:
    code = compile(source_file.read(), filename, "exec")

exec(code, vir_globals) #remove the empty object here !!

print( 'exec: globals.cycleOffset', vir_globals['cycleOffset'] )

and it should to the tricks

You can also take a look at this question and excellent answer from @thefourtheye Using a function defined in an exec'ed string in Python 3

jossefaz
  • 3,312
  • 4
  • 17
  • 40