By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,932 Members | 1,540 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,932 IT Pros & Developers. It's quick & easy.

namespace problems

P: n/a
Hi all, I am trying to get the following to work, but cant seem to do
it the way i want to.

ok, so I come into python and do the following:
>>x = 1
then, i have a file called test.py in which i say:
print x

Now, after having defined x =1 in the python interpreter, i come in and
say:
import test
it has a problem, which i can understand, because it is in its own
namespace,
but even if i say:
from test import *
the interpreter still gives me the error:
NameError: name 'x' is not defined

the only way i can get it to work is if i say: execfile('./test.py')
how can i get this to work by importing and not execfile?

thanks for your help!

Aug 25 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Kiran" <Ki*********@gmail.comwrote in message
news:11*********************@h48g2000cwc.googlegro ups.com...
Hi all, I am trying to get the following to work, but cant seem to do
it the way i want to.

ok, so I come into python and do the following:
>>>x = 1

then, i have a file called test.py in which i say:
print x

Now, after having defined x =1 in the python interpreter, i come in and
say:
import test
it has a problem, which i can understand, because it is in its own
namespace,
but even if i say:
from test import *
the interpreter still gives me the error:
NameError: name 'x' is not defined

the only way i can get it to work is if i say: execfile('./test.py')
how can i get this to work by importing and not execfile?
Dennis gave you one way: import __main__ into test.
Another way to come close is to put the print inside a function.

test.py
---------
def p(): print x

Then your script could say

import test
test.x = 1
test.p()

If you don't already, you need to know that import only executes the code
for a module the *first* time you import it. So normally, top level code
in modules consists of function and class definitions and perhaps the
initialization of a few module-level constants or variables.

Terry Jan Reedy


Aug 25 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.