Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This issue is somewhat discussed in the <a href="http://bugs.python.org/issue4831" rel="nofollow noreferrer">Python3 bug list</a>. Ultimately, to get this behavior, you need to do:</p> <pre><code>def foo(): ldict = {} exec("a=3",globals(),ldict) a = ldict['a'] print(a) </code></pre> <p>And if you check <a href="http://docs.python.org/3.1/library/functions.html#exec" rel="nofollow noreferrer">the Python3 documentation on <code>exec</code></a>, you'll see the following note:</p> <blockquote> <p>The default locals act as described for function <code>locals()</code> 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.</p> </blockquote> <p>Referring back to <a href="http://bugs.python.org/msg79061" rel="nofollow noreferrer">a specific message on the bug report</a>, Georg Brandl says:</p> <blockquote> <p>To modify the locals of a function on the fly is not possible without several consequences: <strong>normally, function locals are not stored in a dictionary, but an array</strong>, 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, <strong>the compiler does not know what "exec" may be bound to, and therefore can not treat is specially</strong>.</p> </blockquote> <p>Emphasis is mine.</p> <p>So the gist of it is that Python3 can better optimize the use of local variables by <em>not</em> allowing this behavior by default.</p> <p>And for the sake of completeness, as mentioned in the comments above, this <em>does</em> work as expected in Python 2.X:</p> <pre><code>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. &gt;&gt;&gt; def f(): ... a = 1 ... exec "a=3" ... print a ... &gt;&gt;&gt; f() 3 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload