exec "statement" VS. exec "statement in globals(), locals()

T

Ted

--------
def f():
ret = 2
exec "ret += 10"
return ret

print f()
--------

The above example prints '12'. However, the following example prints
'2':

--------
def f():
ret = 2
exec "ret += 10" in globals(), locals()
return ret

print f()
--------

According to (http://docs.python.org/ref/exec.html), "In all cases, if
the optional parts are omitted, the code is executed in the current
scope." Don't globals() and locals() comprise the current scope? Why
isn't the output of each example the same?
 
D

Duncan Booth

(e-mail address removed) (Ted) wrote in
According to (http://docs.python.org/ref/exec.html), "In all cases, if
the optional parts are omitted, the code is executed in the current
scope." Don't globals() and locals() comprise the current scope? Why
isn't the output of each example the same?

locals() is a copy of the current scope, not the original. You should never
expect updates to locals() to be reflected in the local variables of the
current scope.

Are you really sure you need to use exec at all? There are very few good
use cases where exec is the appropriate answer to a problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top