467,859 Members | 1,383 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,859 developers. It's quick & easy.

execfile then import back

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.

Jun 2 '06 #1
  • viewed: 1329
Share:
2 Replies
> ########## 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

Jun 2 '06 #2
Dennis Lee Bieber wrote:
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?

Jun 2 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Bo Jacobsen | last post: by
2 posts views Thread by Alex Popescu | last post: by
1 post views Thread by Fernando Perez | last post: by
2 posts views Thread by Dave Westerman | last post: by
5 posts views Thread by George Sakkis | last post: by
1 post views Thread by moijes12 | last post: by
2 posts views Thread by Igor Kaplan | last post: by
reply views Thread by jack112 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.