473,847 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exec Statement Question

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}

----
returns:
1 2 3 3
[ sys.path stuff ....]

Since I'm telling exec to operate only within the context of the
dictionary I give it, why does it still see sys.path and d? I figured
it would throw a NameError.

Is there a way to call exec such that it won't have access to any more
objects than I explicitly give it?

Thanks,

Greg
Apr 9 '07 #1
4 2154
On Apr 8, 11:31 pm, "Gregory Piñero" <gregpin...@gma il.comwrote:
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}

----
returns:
1 2 3 3
[ sys.path stuff ....]

Since I'm telling exec to operate only within the context of the
dictionary I give it, why does it still see sys.path and d? I figured
it would throw a NameError.

Is there a way to call exec such that it won't have access to any more
objects than I explicitly give it?

Thanks,

Greg
I think the way it works is that when the def is parsed, a function
object is created and assigned to the name func1. When the function
object is created, d is "bound" to the global value 3, while a,b,c lie
in wait for arguments to land in their gullets like venus fly traps.
Your dictionary has a key whose value is a reference to the function
object, which already has the value 3 bound to d.
Apr 9 '07 #2
Gregory Piñero <gr********@gma il.comwrote:
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}

----
returns:
1 2 3 3
[ sys.path stuff ....]

Since I'm telling exec to operate only within the context of the
dictionary I give it, why does it still see sys.path and d? I figured
it would throw a NameError.

Is there a way to call exec such that it won't have access to any more
objects than I explicitly give it?
func1 accesses its globals through func1.func_glob als (which you can't
reassign -- it's a read-only attribute).

You may make a new function object w/ a different globals dict...:
>>g = type(func1)(fun c1.func_code, {})
and that will fail (even when called directly, but similarly if exec'd)
as it's missing key 'd' in its globals:
>>g(1, 2, 3)
1 2 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func1
NameError: global name 'd' is not defined
The globals dict you pass to exec is the globals at the time of CALL,
not the globals seen from INSIDE func1; that's always going to be the
func_globals attribute of the function object, so you need to control
that (by suitably building a new function object as you require).
Alex
Apr 9 '07 #3
7stud wrote:
On Apr 8, 11:31 pm, "Gregory Piñero" <gregpin...@gma il.comwrote:
Is there a way to call exec such that it won't have access to any more
objects than I explicitly give it?

I think the way it works is that when the def is parsed, a function
object is created and assigned to the name func1. When the function
object is created, d is "bound" to the global value 3, while a,b,c lie
in wait for arguments to land in their gullets like venus fly traps.
Your dictionary has a key whose value is a reference to the function
object, which already has the value 3 bound to d.
Not exactly. As Georg Brandl said, the function has a reference to the
*globals* currently in use when it was defined, not directly to the
name "d".

To the OP: If you want a function with almost "empty" globals, compile
it the same way you used to execute it:
>>text = """def func1(a):
.... print a
.... print b
....
.... func1(3)
.... print func1.func_glob als.keys()
.... """
>>>
exec text in {}
3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 5, in ?
File "<string>", line 3, in func1
NameError: global name 'b' is not defined
>>exec text in {"b": 123}
3
123
['__builtins__', 'func1', 'b']
>>>
I said *almost* empty because Python may insert other keys into the
globals, like __builtins__ above (see http://docs.python.org/ref/exec.html)

--
Gabriel Genellina

Apr 9 '07 #4
Thanks for the responses everyone. That does make sense to me now.

-Greg

Apr 10 '07 #5

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

Similar topics

5
5784
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):
5
1544
by: Carlos Ribeiro | last post by:
Hello all, I have a module that retrieves code snippets from a database to be executed on the fly . As I make heavy use of accented characters inside strings (I'm in Brazil), it came to my attention that the exec statement does not implement PEP 263 encoding checking. It does not issue any warning when fed with arbitrary code that includes non-ASCII characters. I am not sure if this is: 1) a design feature;
1
2238
by: Andr? Roberge | last post by:
I have the following two files: #--testexec.py-- def exec_code(co): try: exec co except: print "error" #-- test.py--
0
10233
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
8
3328
by: R. Bernstein | last post by:
In doing the extension to the python debugger which I have here: http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 I came across one little thing that it would be nice to get done better. I notice on stack traces and tracebacks, an exec or execfile command appears as a stack entry -- probably as it should since it creates a new environment. However the frame information for exec or execfile looks like this:...
5
2441
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
4
2377
by: Michael | last post by:
Hi, I'm having difficulty finding any previous discussion on this -- I keep finding people either having problems calling os.exec(lepev), or with using python's exec statement. Neither of which I mean here. Just for a moment, let's just take one definition for one of the
6
3638
by: vasudevram | last post by:
Hi group, Question: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? I wrote a function to generate other functions using something like eval("def foo: ....") but it gave a syntax error ("Invalid syntax") with caret pointing to the 'd' of the def keyword.
0
318
by: Stef Mientki | last post by:
Terry Reedy wrote: The locals of the code block where the instance of this class is created. No I think it's indeed handled as function call. I now that, because the globals (and sometimes ??? the locals) of the codeblock where the class is initiated is changed. Yes I've already done that, and this yields exactly the same results. So I guess that the exec-function is already there and doesn't differ from the exec-statement. And indeed...
7
2653
by: gregory.lielens | last post by:
Hi, I am using a small python file as an input file (defining constants, parameters, input data, ...) for a python application. The input file is simply read by an exec statement in a specific dictionary, and then the application retrieve all the data it need from the dictionary... Everything is working nicely, but I'd like to have something a little bit more robust regarding input file errors: now any error in the python input script...
0
9879
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9727
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10643
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10706
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
7050
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5907
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4521
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
2
4113
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3158
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.