execfile then import back

  • Thread starter overly.crazy.steve
  • Start date
O

overly.crazy.steve

I am seeing something strange with execfile. I've simplified the code
to:

########## t.py ##########
print "here"
v = None

def f():
global v
v = 6

if __name__ == "__main__":
f()
print "0:", v
execfile("x.py")
print "0:", v
execfile("y.py")
print "0:", v

########## x.py and y.py (they are identical) ##########
import testexec
print "1:", v, testexec.v
testexec.v = 7

Runing "python t.py" (with Python 2.4.2), the printout I got is:

here
0: 6
here
1: 6 None
0: 6
1: 6 7
0: 6

So there is apparently 2 different instances of v at run time. Can
someone please explain (1) why this is the case, and (2) assuming this
is correct behavior, how I can avoid this? Thanks.
 
O

overly.crazy.steve

########## x.py and y.py (they are identical) ##########
import testexec
print "1:", v, testexec.v
testexec.v = 7

Oops, testexec should be changed to t instead. That is:

########## x.py and y.py (they are identical) ##########
import t
print "1:", v, t.v
t.v = 7
 
D

Dennis Lee Bieber

Oops, testexec should be changed to t instead. That is:

########## x.py and y.py (they are identical) ##########
import t
print "1:", v, t.v
t.v = 7

And the problem you are seeing is that the initial "v" in the t.py
that you "run", is considered "__main__.v", NOT "t.v"
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
O

overly.crazy.steve

Dennis said:
And the problem you are seeing is that the initial "v" in the t.py
that you "run", is considered "__main__.v", NOT "t.v"

Yes, the 2 different copies of v apparently imply that __main__ and t
are 2 different modules. But I had expected __main__ to be an alias of
t. Can you point out the passage in Python doc that explains this?
 

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

Tic Tac Toe Game 2
Bug in execfile? 1
Range / empty list issues?? 1
Register Question 0
Gray Scott model in FEniCS 0
Mutability issue 1
Minimum Total Difficulty 0
Nested module import clutters package namespace? 1

Members online

Forum statistics

Threads
474,297
Messages
2,571,536
Members
48,282
Latest member
Xyprime

Latest Threads

Top