Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > exec "statement" VS. exec "statement in globals(), locals()

Reply
Thread Tools

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

 
 
Ted
Guest
Posts: n/a
 
      07-21-2004
--------
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?
 
Reply With Quote
 
 
 
 
Duncan Booth
Guest
Posts: n/a
 
      07-22-2004
http://www.velocityreviews.com/forums/(E-Mail Removed) (Ted) wrote in
news:(E-Mail Removed) 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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Net::SSH.exec Using the "exec" method interactively Guillermo Riojas Ruby 0 11-26-2010 05:17 PM
Runtime.exec(String[]) Doesn't Always Work, bBut Runtime.exec(String) Does Hal Vaughan Java 11 05-22-2006 04:49 PM
Exec/System call with spaces in exec path problem ... Random Task Perl Misc 12 12-04-2005 10:03 AM
exec "statement" VS. exec "statement" in globals(), locals() tedsuzman Python 2 07-21-2004 08:41 PM
Backup Exec 9.1: The Backup Exec job engine system service is not responding Christian Falch Computer Support 1 06-23-2004 02:22 AM



Advertisments