473,320 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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

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

print f()
-----

The above prints '12', as expected. However,

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

print f()
------

prints '2'. 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() consist of the current
scope? Why aren't the two examples above equivalent?

Jul 18 '05 #1
2 4162
From Python Manual:

execfile(file[, globals[, locals]])
This function is similar to the exec statement, but parses a file instead
of a string. It is different from the import statement in that it does not
use the module administration -- it reads the file unconditionally and does
not create a new module.2.2
The arguments are a file name and two optional dictionaries. The file is
parsed and evaluated as a sequence of Python statements (similarly to a
module) using the globals and locals dictionaries as global and local
namespace. If the locals dictionary is omitted it defaults to the globals
dictionary. If both dictionaries are omitted, the expression is executed in
the environment where execfile() is called. The return value is None.

Warning: 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 execfile() returns. execfile() cannot be used reliably
to modify a function's locals.

I think the Warning explains it.

You can do:

def f():
l={'ret':2}
exec("ret += 10", globals(), l)
return l['ret']
print f()

12

"tedsuzman" <te*******@yahoo.com> wrote in message
news:ma*************************************@pytho n.org...
-----
def f():
ret = 2
exec "ret += 10"
return ret

print f()
-----

The above prints '12', as expected. However,

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

print f()
------

prints '2'. 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() consist of the current
scope? Why aren't the two examples above equivalent?

Jul 18 '05 #2
Hi !
In the syntax 2, because "ret=2", "ret" is local to f()


Try :

chaine="""global ret
ret=ret+10"""

def f():
global ret
ret = 2
exec chaine in globals(), locals() #now, idem exec(chaine)
return ret

print f() #==> 12


Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Mensan | last post by:
I am trying to compute the differnece between two dwords in visual basic and keep getting the wrong value being computed. I have the following structure defind: Public Type HighLowQuote...
5
by: Toby Donaldson | last post by:
Hi all, I'm designing an educational application that will run Python code and check the output against a pre-define answer. I want to use the "exec" statement to run the code, but I don't know...
1
by: Ted | last post by:
-------- def f(): ret = 2 exec "ret += 10" return ret print f() -------- The above example prints '12'. However, the following example prints
4
by: Flapper | last post by:
Help please, Have a situation when converting from Oracle SP's to SQL SP's. The old oracle cursor was roughly as follows CURSOR cur_rsStock IS select * from (select StockRowId, CategoryId
5
by: charliewest | last post by:
I've implemented the USING statement to ensure that my newly created sql connection closes when my method is finished using it. The USING statement is wrapped in try/catch error handling statement....
28
by: Steven Bethard | last post by:
Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions!...
5
by: TPJ | last post by:
I have the following code: ----------------------------------- def f(): def g(): a = 'a' # marked line 1 exec 'a = "b"' in globals(), locals() print "g: a =", a
0
by: Steven Bethard | last post by:
Felipe Almeida Lessa wrote: > Em Sex, 2006-04-14 às 09:31 -0600, Steven Bethard escreveu: >> Here's the code I used to test it. >> >> >>> def make(callable, name, args, block_string): >> ... ...
4
by: =?ISO-8859-1?Q?Gregory_Pi=F1ero?= | last post by:
I'm curious why this code isn't working how I expect it to: import sys d=3 def func1(a,b,c): print a,b,c,d print sys.path exec "func1(1,2,3)" in {'func1':func1}
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.