首頁  >  文章  >  後端開發  >  Python 2 與 Python 3 之間 `exec` 的行為有何不同?

Python 2 與 Python 3 之間 `exec` 的行為有何不同?

Patricia Arquette
Patricia Arquette原創
2024-11-14 13:51:01844瀏覽

How does the behavior of `exec` differ between Python 2 and Python 3?

Behavior of exec in Python 2 and Python 3

In Python 2, the exec statement acted as a statement, allowing developers to dynamically execute Python code. However, in Python 3, exec became a function, exec(), resulting in some behavior differences.

Exec Function Behavior

One noticeable distinction is the handling of local variables. In Python 2, using the exec statement could modify local variables within the function scope. For instance:

def test():
    a = 42
    exec("a = 100")
    print(a)  # Output: 100

However, in Python 3, this functionality is no longer available. Executing code using the exec() function does not modify local variables, even if they are declared beforehand. This is because function scopes are always optimized in Python 3.

Achieving Python 2 Behavior in Python 3

To replicate the behavior of Python 2, where exec modifies local variables, Python 3 offers a different approach. Developers need to use a new namespace instead of the local scope. This can be done by creating a dictionary and passing it to the exec() function:

def test():
    a = 42
    namespace = {}
    exec("a = 100", namespace)
    print(a)  # Output: 42
    print(namespace['a'])  # Output: 100

In this example, the exec() function uses the namespace dictionary for variable manipulation. The namespace is then used to retrieve the modified value of 'a'.

Coercion of Local Variables

In Python 3, some coerced variables can cause unexpected behavior with exec. The following example demonstrates:

def test():
    a = 42
    d = locals()
    exec("a = 100\nprint('b:', a)", globals(), d)

    print(a)  # Output: 42
    print(d['a'])  # Output: 100

Here, the 'a' variable inside the exec() function is coerced to the 'b' variable, resulting in a different value being printed. This illustrates the limitations of locals() in influencing variables declared using exec().

以上是Python 2 與 Python 3 之間 `exec` 的行為有何不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn