Home > Article > Backend Development > How Does Exec Function Behavior Differ Between Python 2 and Python 3?
Exec Function Behavior in Python 2 versus Python 3
The exec statement exhibits noticeable differences in behavior between Python 2 and Python 3. In Python 2, exec acted as a statement, effectively changing local variables within function scope.
However, in Python 3, exec() becomes a function. This prevents the modification of local variables inside functions, despite being possible in Python 2. Moreover, even previously declared variables are not modifiable.
The locals() function only allows unilateral updating of local variables. For example, in the following Python 2 code:
def foo(): a = 'spam' locals()['a'] = 'ham' print(a) # prints 'spam'
The assignment of 'ham' to locals()['a'] does not affect the value of the variable 'a' within the function, and 'spam' remains printed.
In Python 2, exec explicitly copied variables found in locals() back to the function locals using PyFrame_LocalsToFast. However, in Python 3, this behavior is no longer possible.
To achieve the desired behavior in Python 3, one must employ a new namespace (for example, a dictionary) during the exec() call. This can be seen in the following Python 3 code:
def execute(a, st): namespace = {} exec("b = {}\nprint('b:', b)".format(st), namespace) print(namespace['b'])
The exec() documentation explicitly states the limitations imposed on locals() usage:
"Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns."
The above is the detailed content of How Does Exec Function Behavior Differ Between Python 2 and Python 3?. For more information, please follow other related articles on the PHP Chinese website!