473,405 Members | 2,262 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,405 software developers and data experts.

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 2139
On Apr 8, 11:31 pm, "Gregory Piñero" <gregpin...@gmail.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********@gmail.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_globals (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)(func1.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...@gmail.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_globals.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
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...
5
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...
1
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
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...
8
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...
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
4
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...
6
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...
0
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...
7
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.