This is the code:
def test():
c = 0
exec('c = 4 + 5')
print('result', c)
The value of c
is 0. What can I do to fix it, let the value of c
changed in exec()
function?
This is the code:
def test():
c = 0
exec('c = 4 + 5')
print('result', c)
The value of c
is 0. What can I do to fix it, let the value of c
changed in exec()
function?
In cpython, you can't do what you want inside a function. That's because a function's local namespace can't be easily edited by other code (editing the dictionary returned by locals()
doesn't do it). If instead you call exec
from the top level of your module, it will work as you want, but it is still probably a bad idea.
A better approach may be to use a namespace dictionary. You can pass it to exec
and the change will appear there, rather than in the function's local namespace or the module's global namespace:
def test():
namespace = {'c': 0}
exec('c = 4 + 5', namespace)
print('result', namespace['c'])
exec
and other lines were not inside the test
function. That's because an exec
call with no namespace arguments is equivalent to exec(whatever, globals(), locals())
. Inside a function, you can't usefully save values to the dictionary returned by locals
, so that doesn't do you much good. But at top level, locals()
returns the same dictionary as globals()
, and you can modify that dictionary and see the results in the global namespace.
Sep 7, 2018 at 18:33