That depends on you notion of update:
Remember that Python is a compiled language: A module is read and compiled into byte code. So when you change the source file, nothing happens because the code was already compiled.
Simply importing a module repeatedly also does nothing, the importer simply checks sys.modules
and returns the already existing module from there. A module load is only triggered when you load an unknown module (according to sys.modules
).
There is also no auto-check for changed source files, so source files are not automatically recompiled when they have changed.
However, compiled files (.pyc
, .pyo
) are checked against their source files before they are used. If the corresponding source files are newer or have a different size, recompilation happens for fresh loads (not on import, on load). Note, however, that the .pyc
timestamp resolution is only 32 bits, so the actual file system timestamp is truncated.
You can jump through some serious hoops to make Python import a changed source file:
sys.path.insert(0, os.getcwd())
with open("B.py", 'w') as bfile:
bfile.write("""
class B:
def act(self):
print "First version"
""")
import B
first_class = B.B()
with open("B.py", 'w') as bfile:
bfile.write("""
class B:
def act(self):
print "Second version"
""")
try:
os.unlink('B.pyc')
except OSError:
pass
try:
os.unlink('B.pyo')
except OSError:
pass
reload(B)
second_class = B.B()
first_class.act()
second_class.act()
This is actually by coincidence, but the code shows one of the real problems that occur with reimporting and recompilation. Because the two B.py
s are created quickly after another, their timestamps more often than not compare equal to the .pyc
timestamp. You might get lucky and hit the actual timestamp flip, but that's just luck. Since the files are also the same size on Unix (note the extra newline for the second version), the file size check also reports both source files to be equal.
If you remove the unlink()
operations, you --most of the time-- get no module recompile. Instead you get the version version of B
loaded from the .pyc
file, even though it does not match B.py
any more.
In any case, the code objects from the initial import are retained. In this example, first_class
is from the initial version of B.py
, second_class
is from the updated version. The first class is already compiled into byte code and in memory, it does not change just because you change its source file.
For all practical purposes, both classes are from different modules that incidentally happen to have the same source file.
This is probably only useful for debugging and I strongly advise against using it for anything productive. This is especially true, if your module has more than the single source file.
That said, reload()
doesn't exist any more in Python 3, because it never worked as expected even in Python 2.