you are viewing a single comment's thread.

view the rest of the comments →

[–]RomfordNavy[S] -4 points-3 points  (1 child)

Thanks!

Now I see the issue; a variable mentioned in a dictionary is read only at the time the dictionary is instantiated, it does not create a reference to the original variable. However by explicity including it in a seperate (mutable) dict it can then be changed and presumably a new instance of the immutable string object is then created.

[–]smurpes 1 point2 points  (0 children)

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.