Problem with exec

J

Justus Schwabedal

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top