I have a global variable with a variable name, so using it is a bit difficult. (Yes, go ahead and tell me that exec is a bad solution, because I would be happy to learn a better one.) This is within a function that I need to run recursively, so global variables can only be used with extreme caution. In addition, the function creates new variables and I can't say beforehand what they will be. This recursive function was working until I added the pickle parts, to save and restore variables and avoid unnecessary repetitions of the calculations. Here is a snippet:
strVar = 'c%sc%dX' % (strJ, kIn)
fName = '%s\\%s.pckl' % (pickle_dir, strVar)
if os.path.isfile(fName):
#retVal = 0 # default to avoid undefined error
strSym = 'retVal = %s' % (strVar)
exec(strSym, globals(), locals())
return retVal
#strSym = 'global %s; return %s' % (strVar, strVar)
#exec(strSym, globals())
In the current test, when this code is run the first time, strVar contains a string with the name of the variable, i.e. 'cm1c0X' and the variable cm1c0X is global and contains the value integer 0.
In the line "return retVal", Visual Studio puts a wavy underline under retVal and says it is not defined. When I run the code, this statement produces an exception saying that the local variable 'retVal' is referenced before assignment. Also, retVal does not appear in the list of local or global variables.
My guess: the exec statement does in fact work, and produces the variable retVal within the scope of exec, but not within the scope of my "if" statement. When I use the last 2 lines instead of this, I get "return outside function", so presumably the return statement is in the scope of exec and not within the scope of the "if" statement or the function surrounding it.
So, I am looking for some way to assign a global variable to a local variable that is within the scope of my code. Maybe I need to use something other that globals() and locals(). I read that I could use a custom-built dictionary, but the example code didn't explain what needs to come after the colon in the dictionary, so I haven't understood it yet.