classification
Title: exec inside a function
Type: behavior Stage:
Components: Interpreter Core Versions: Python 3.0
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: beazley, georg.brandl
Priority: normal Keywords:

Created on 2008-11-27 17:35 by beazley, last changed 2008-11-27 18:07 by beazley. This issue is now closed.

Messages (3)
msg76508 - (view) Author: David M. Beazley (beazley) Date: 2008-11-27 17:35
Is the following code valid Python 3 or not?

def foo():
    x = 1
    exec("x = 42")
    print(x)    # Prints 1  (exec has no effect)

I know there are a variety of issues surrounding exec(), function 
bodies, and other matters.   Just wondering if this sort of thing is now 
forbidden or not.
msg76509 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2008-11-27 17:47
It is "valid" Python 3 and the lack of an effect on the local is correct.

From Python 3 on, "exec" is a function and therefore lacks the special
magic properties it had in Python 2 that made it possible execute the
code "as if it just was written there".

In effect, what exec() modifies here is similar to what locals()
returns: a mere copy of the local namespace.
msg76511 - (view) Author: David M. Beazley (beazley) Date: 2008-11-27 18:07
For what it's worth, I hope this behavior gets well-documented.  Thanks.
History
Date User Action Args
2008-11-27 18:07:18beazleysetmessages: + msg76511
2008-11-27 17:47:21georg.brandlsetstatus: open -> closed
resolution: wont fix
messages: + msg76509
nosy: + georg.brandl
2008-11-27 17:35:01beazleycreate