exec's Impact on Local Variables: A Dive In
The exec function, a Python staple for dynamic code execution, poses an intriguing query: can it update local variables within a function?
The Python 3 Dilemma
In Python 3, the following code snippet fails to update a local variable as one might expect:
def f(): a = 1 exec("a = 3") print(a)
Instead of the anticipated '3', it alarmingly prints '1'!
The Python 2 Behavior
Curiously, the same code in Python 2 would indeed update the local variable, printing '3'. This disparity arises from a fundamental change in how Python handles local variables.
The Locals Dilemma
Unlike in Python 2, Python 3 stores local variables in a frozen array optimized at compile time. This efficiency comes at the cost of prohibiting runtime modifications to the locals. Thus, the default exec call in Python 3 cannot successfully alter local variables.
The Magic of Locals()
To bypass this limitation and update local variables, one must explicitly pass a locals dictionary to exec. This dictionary will store the updated local variables after the execution of the dynamic code. The revised code looks like this:
def foo(): ldict = {} exec("a = 3", globals(), ldict) a = ldict['a'] print(a)
Implications for Exec()
The Python 3 documentation explicitly cautions against modifying the default locals() dictionary while using exec, as this can lead to unpredictable behavior. For safety, one should always pass an explicit locals dictionary to exec when intending to update local variables.
The Curious Optimizations of Python
Georg Brandl's insightful comments on the Python bug report highlight that Python 3's optimization for local variables led to the current behavior. The compiler, unable to distinguish custom exec functions from Python's own, cannot offer them special treatment. Hence, the default exec cannot alter locals.
Python 2's Exception
In Python 2, the old exec statement worked differently. It allowed local variables to be modified dynamically by virtue of the compiler's special handling of the built-in exec.
Conclusion
The exec call in Python 3 necessitates a subtle change in approach to modify local variables. By employing an explicit locals dictionary, developers can leverage the power of dynamic code execution while maintaining control over their local variables.
The above is the detailed content of Does `exec()` Update Local Variables in Python 3, and If Not, How Can It Be Made To?. For more information, please follow other related articles on the PHP Chinese website!