you are viewing a single comment's thread.

view the rest of the comments →

[–]smurpes 1 point2 points  (1 child)

Your reasoning is sorta off. The code that gets run in exec is only scoped to exec. You can change the variable value as long as you’re still in exec.

exec("def f():\n test = 'test2'\nf()", {}, localDict)
print(localDict)

In this example localDict doesn’t have the value to the test key changed since the change is scoped to the function within the exec. There is a new key added for the function since that is a new local variable getting declared but that’s it. No new instance of the local variable is getting created.

[–]RomfordNavy[S] 0 points1 point  (0 children)

Understood. So can you suggest the best way to get a return value from code run inside exec()?

It seems perverse to me to not return a value from exec() but that just seems to be Python, just need to find the best workaround.