I used to think that once a module was loaded, no re-importing would be done if other files imported that same module, or if it were imported in different ways. For example, I have mdir/__init__.py
, which is empty, and mdir/mymod.py
, which is:
thenum = None
def setNum(n):
global thenum
if thenum is not None:
raise ValueError("Num already set")
thenum = n
def getNum():
if thenum is None:
raise ValueError("Num hasn't been set")
return thenum
First few use cases from the same file go according to expectation. This file is ./usage.py
, the same folder mdir
is in:
import mdir.mymod
mdir.mymod.setNum(4)
print mdir.mymod.getNum()
from mdir import mymod
print mymod.getNum()
from mdir.mymod import *
print getNum()
try:
setNum(10)
except ValueError:
print "YHep, exception"
The output is as expected:
4
4
4
YHep, exception
However, if I muck with the system path, then it looks like the module is imported anew:
#BEHOLD
import sys
sys.path.append("mdir")
import mymod
try:
mymod.getNum()
except ValueError:
print "Should not have gotten exception"
mymod.setNum(10)
print mymod.getNum()
print mdir.mymod.getNum()
That code, running after the previous code, yields:
Should not have gotten exception
10
4
What gives?