Issue
In file1.py:
def foo():
import file2
print "I'm the old file1.py"
file2.bar()
if __name__ == '__main__':
foo()
In file2.py
print "I'm the old file2.py"
def bar():
print "I'm in the old file2.bar()"
On line 5 of the interactive session below, after making modifications to file1.py and file2.py changing all three occurrences of the word old
to new
, the new
code in file2.py is still not used.
wim@wim-ubuntu:~/sandpit$ ipython
>>> run file1.py
I'm the old file2.py
I'm the old file1.py
I'm in the old file2.bar()
>>> !rm file2.pyc
>>> # modify file1, file2
>>> run file1.py
I'm the new file1.py
I'm in the old file2.bar()
Where is it getting the old code from file2.py from?
I must misunderstand something, because I thought (from ipython help on run
):
The file is executed in a namespace initially consisting only of
__name__ == '__main__'
andsys.argv
constructed as indicated. It thus sees its environment as if it were being run as a stand-alone program
I've deleted the .pyc file, and can see from the command whos
that there is no file2 module present in the namespace. But why is the import not executed again when running file1 a second time?
Solution
run
does not start a new Python process, but rather executes your code in the current one--not in the current namespace, but in the current Python process, the note from the documentation explains. Because of this, sys.modules
is still around and the old cached module is used. (Are you familiar with the way Python caches imported modules normally?)
To fix this, run in a new Python process each time. reload
is more than a little problematic and can lead to headaches that I find aren't worth it.
Answered By - Mike Graham
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.