Home > Backend Development > Python Tutorial > How Can I Update Local Variables Within Python's `exec` Function?

How Can I Update Local Variables Within Python's `exec` Function?

Barbara Streisand
Release: 2024-12-06 01:58:10
Original
684 people have browsed it

How Can I Update Local Variables Within Python's `exec` Function?

Overcoming Variable Update Limitations with Python Exec

In Python, the exec function allows for the dynamic execution of Python code at runtime. However, when used with local variables, it can behave unexpectedly.

The Problem:

Consider the following code:

def f():
    a = 1
    exec("a = 3")
    print(a)

f()
Copy after login

In Python 2, this code would print 3, indicating that the local variable a has been updated within the exec call. However, in Python 3, it prints 1, raising the question of how to get local variables updated during exec calls.

The Solution:

To address this issue, you need to explicitly pass a locals dictionary to the exec function:

def foo():
    ldict = {}
    exec("a = 3", globals(), ldict)
    a = ldict['a']
    print(a)
Copy after login

By using locals(), you create a new local variable namespace for the exec call. Modifications to this namespace will be reflected in the foo function's local scope.

Key Points:

  • Python 3 optimizes local variable storage, affecting the behavior of exec.
  • The default locals dictionary for exec cannot be modified in Python 3.
  • Using an explicit locals dictionary allows for local variable updates within exec calls.

The above is the detailed content of How Can I Update Local Variables Within Python's `exec` Function?. 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