[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Problem with exec

Justus Schwabedal

3/12/2008 11:59:00 PM

Dear python users!
I try to setted up compile-free parallelism using the exec command.
However I had some problems with namespaces which I find mysterious
although I managed to work around. But the workaround is not nice, so
I wonder if there are ways.
I do the following,

bash-3.2$ cat execBug.py
#! /usr/bin/python
header="""
from scipy import randn
def f():
return randn()
"""
def g(head):
exec header
return f()
print "g(header) =",g(header)

bash-3.2$ ./execBug.py
g(header) =
Traceback (most recent call last):
File "./execBug.py", line 10, in <module>
print "g(header) =",g(header)
File "./execBug.py", line 9, in g
return f()
File "<string>", line 4, in f
NameError: global name 'randn' is not defined

However this works:

bash-3.2$ cat execBug.py
#! /usr/bin/python
header="""
from scipy import randn
def f():
return randn()
"""
exec header
print "f() =",f()

bash-3.2$ ./execBug.py
f() = 1.44707148916

If for the first example I add "global randn", it works again.
However I do not understand how the nested namespaces interact here.
Isn't this an unwanted feature in the functionality?
I'm looking foreward to your comments, Justus