Home > Backend Development > Python Tutorial > Why Doesn't exec Update Local Variables in Python 3, and How Can I Fix It?

Why Doesn't exec Update Local Variables in Python 3, and How Can I Fix It?

Linda Hamilton
Release: 2024-12-14 20:20:11
Original
790 people have browsed it

Why Doesn't exec Update Local Variables in Python 3, and How Can I Fix It?

How to Update Local Variables Using exec in Python 3

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()
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template