You are almost there. You are trying to change a global variable, so you need to add an operator global:
old_string = "didn't work"
new_string = "worked"
def function():
exec("global old_string; old_string = new_string")
print(old_string)
function()
If you run the following version, you will see what happened in your version:
old_string = "didn't work"
new_string = "worked"
def function():
_locals = locals()
exec("old_string = new_string", globals(), _locals)
print(old_string)
print(_locals)
function()
output:
didn't work
{'old_string': 'worked'}
As you launched it, you tried to change the local variables of the function in exec, which is essentially undefined behavior. See warning in execdocs :
: , locals() : . , , exec() .
locals():
: ; , .