execfile then import back

overly.crazy.steve at gmail.com overly.crazy.steve at gmail.com
Thu Jun 1 20:30:30 EDT 2006


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.




More information about the Python-list mailing list