473,545 Members | 1,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4177
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*******@yaho o.com> wrote in message
news:ma******** *************** **************@ python.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="""globa l 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
3236
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 TradeDate As String OpenPrice As Double HighPrice As Double LowPrice As Double ClosePrice As Double
5
5771
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 how to get output from it. For instance, exec works like this: >>> code = """ for i in xrange(1, 5):
1
1680
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
7668
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
8731
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. This works fine. When i try to implement the "SqlTransation" class, the code does not work as the SqlTransation object is out-of-scope in the...
28
2914
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! PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $
5
2420
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
1327
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): >> ... try: >> ... make_dict = callable.__make_dict__ >> ... except AttributeError: >> ... make_dict = dict >> ... block_dict...
4
2145
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
7478
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7410
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7668
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7437
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1901
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.