I thought this would print 3, but it prints 1:
def f(): a = 1 exec("a = 3") print(a)
Exec function can dynamically execute code of python programs. The code can be passed in as string or object code to this function. The object code is executed as is while the string is first parsed and checked for any syntax error. If no syntax error, then the parsed string is executed as a python statement.
Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed. If it's an object code, then it is simply executed.
This issue is somewhat discussed in the Python3 bug list. Ultimately, to get this behavior, you need to do:
def foo(): ldict = {} exec("a=3",globals(),ldict) a = ldict['a'] print(a)
And if you check the Python3 documentation on exec
, you'll see the following 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.
That means that one-argument exec
can't safely perform any operations that would bind local variables, including variable assignment, imports, function definitions, class definitions, etc. It can assign to globals if it uses a global
declaration, but not locals.
Referring back to a specific message on the bug report, Georg Brandl says:
To modify the locals of a function on the fly is not possible without several consequences: normally, function locals are not stored in a dictionary, but an array, whose indices are determined at compile time from the known locales. This collides at least with new locals added by exec. The old exec statement circumvented this, because the compiler knew that if an exec without globals/locals args occurred in a function, that namespace would be "unoptimized", i.e. not using the locals array. Since exec() is now a normal function, the compiler does not know what "exec" may be bound to, and therefore can not treat is specially.
Emphasis is mine.
So the gist of it is that Python3 can better optimize the use of local variables by not allowing this behavior by default.
And for the sake of completeness, as mentioned in the comments above, this does work as expected in Python 2.X:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f(): ... a = 1 ... exec "a=3" ... print a ... >>> f() 3
If you are inside a method, you can do so:
class Thing(): def __init__(self): exec('self.foo = 2') x = Thing() print(x.foo)
You can read more about it here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With