I have a function that accepts a string with source code with some definitions, exec
s it - and then gets new definitions from locals()
.
def do_exec(code):
exec(code)
print(locals()['x'])
do_exec('x = 5')
this works as expected.
However, when I try to do this:
def do_exec_2(code):
exec(code)
x = locals()['x']
print(x)
do_exec_2('x = 5')
I get an error:
KeyError: 'x'
why is that?