Problem:
When using exec in Python 3 to execute a string of code within a function, local variables within the function are not updated. This issue arises due to Python 3's efficient optimization of local variable storage.
Example:
def f(): a = 1 exec("a = 3") print(a) f()
This code is expected to print 3 but instead prints 1.
Solution:
To modify local variables using exec, an explicit local dictionary must be passed. This can be achieved as follows:
def foo(): ldict = {} exec("a = 3", globals(), ldict) a = ldict['a'] print(a)
Explanation:
Python 3 stores local variables in an array to optimize their access. However, exec's default behavior doesn't allow for modification of local variables. By passing an explicit local dictionary, the variables can be assigned to the dictionary, and their modified values can be accessed through it.
Python 2 vs Python 3:
In Python 2, this behavior worked as expected due to an optimization mechanism that allowed functions with exec to have non-optimized local variable storage. However, in Python 3, this optimization is no longer possible, leading to the observed behavior.
Note:
It's important to remember that passing an explicit local dictionary should only be done when necessary, as it removes the optimization benefit offered by Python 3's default handling of local variables.
The above is the detailed content of Why Doesn't exec Update Local Variables in Python 3, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!