Search code examples
pythonpython-3.xfunctionexecpython-exec

Command exec in a function, name error - python3


I'm begginer in Python and I'm in front of a problem that I can't understand. I tried to just define a variable with a exec() and then just print it. And it's working well. BUT when I do the same code in a function, it's not working...

Example :

def fonct():
    possibilite = [0,1,2,3]
    testc = 0
    testl = 1
    commande = "proba"+str(testc+1)+str(testl)+" = possibilite"
    exec(commande)
    print(commande)
    print(proba11)

The same thing but not in a function has for result, that the command print(proba11) returns [0,1,2,3] so it works. But for the example I got this :

proba11 = possibilite
NameError: name 'proba11' is not defined

There is no stories about globals or locals, everything is local...


Solution

  • Updating the local variables with exec() in Python 3 is tricky due to the way local variables are stored. It used to work in Python 2.7 and earlier.

    To workaround this, you need to

    • Pass an explicit locals dictionary to exec
    • Grab the newly defined variable from the updated locals dictionary

    Like so:

    def fonct():
        possibilite = [0, 1, 2, 3]
        testc = 0
        testl = 1
        varname = "proba" + str(testc + 1) + str(testl)
        commande = varname + " = possibilite"
        _locals = locals()
        exec(commande, globals(), _locals)
        proba11 = _locals[varname]
        print(proba11)
    

    Which works as expected.

    You can read more about it here: