469,936 Members | 2,402 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,936 developers. It's quick & easy.

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

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?
Jul 18 '05 #1
1 1527
ro*******@gmail.com (Ted) wrote in
news:9a**************************@posting.google.c om:
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.
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Toby Donaldson | last post: by
5 posts views Thread by Carlos Ribeiro | last post: by
28 posts views Thread by Steven Bethard | last post: by
5 posts views Thread by TPJ | last post: by
4 posts views Thread by =?ISO-8859-1?Q?Gregory_Pi=F1ero?= | last post: by
2 posts views Thread by Danny Shevitz | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.