Home > Software engineering >  Python: exec() fucntion not working in Flask
Python: exec() fucntion not working in Flask

Time:08-27

In my Flask application I want to execute code coming from a database. But the exec function seems not to work. To test it in one of my route I put the simple code:

x = 0
exec("x = 10", globals(), locals())
print(x)

There is no error but the value of x stays at 0. Am I missing something?

CodePudding user response:

working fine, value changed to 10, see for yourself, enter image description here

CodePudding user response:

Your code is not failing to be executed, it's just not updating the local variables for your function (for example, try replacing the string being executed with a print statement instead of a variable assignment).

According to https://docs.python.org/3/library/functions.html#exec:

[...] modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

Hopefully someone else manages to explain why locals aren't shared between exec and the function scope when running inside a flask view, but if you need to do so one workaround could be:

_vars = {'x': 0}
exec("x = 10", _vars)
print(_vars['x'])
  • Related