Python exec NameError

python, scope

Solution

Assuming you have a good reason to use `exec`, which is an assumption you should double-check.

You need to supply the global and local scope for the `exec` function. Also, the "program" string needs to actually run instead of just defining a function. This will work:

prog = """
x[0] = y[1]
z[0] = x[0]
out = z[0]
"""

def runExec(stringCode):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    exec(stringCode, globals(), locals())
    return out

print runExec(prog)

Problem

I have a string variable containing a function. the function looks like this: ``` def program(): x[0] = y[1] z[0] = x[0] out = z[0] ``` This is within a method: ``` def runExec(self, stringCode): x = [1,2,3,4] y = [5,6,7,8] z = [6,7,8,9] exec stringCode return out ``` I am receiving a NameError, it seems x, y and z are not accessible from the stringCode exec ? How can I make these variables accessible, do I have to pass them in some way ? Thanks

Original source