I don't have enough reputation points to add comments, but I would like to mention that the previous answer by DrM does not work (inside a function):
def test():
exec( 'a = 3', globals(), locals() )
print(a)
test()
This code gives an error in Python 3:
NameError: name 'a' is not defined
I tried some methods using the compile
function suggested in other forums, but they still do not work for me (at least with the options I have seen mentioned).
According to my research, this the closest code that I have seen working:
def test():
lcls = locals()
exec( 'a = 3', globals(), lcls )
a = lcls["a"]
print(f'a is {a}')
test()
It successfully prints:
a is 3
I think this is an important topic overall. Sometimes when you work with symbolic algebra libraries, like Sympy, defining variables though the exec
function can be very convenient for Scientific Computing.
I hope somebody knows a good answer to the problem.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…