Reputation: 231
I love ipython, but I've discovered a problem with %run: imported modules are not reloaded when %run is called repeatedly.
Suppose file ex1.py contains the lines:
import ex2
ex2.x.append(1)
print ex2.x
And file ex2.py contains:
x = []
Now, running python ex1.py from the command line repeatedly prints [1] every time. But invoking %run ex1.py
from within ipython repeatedly prints [1], [1,1], [1,1,1], etc. This is because module ex2.py is not reloaded. So we have a problem: the ipython run-script protocol is not reflecting "real world" behavior.
Note:
%load_ext autoreload
%autoreload 2
does not help. Those lines will get ex2.py reloaded only if a change has been made to the ex2.py file. If we don't make any changes, or only make changes to ex1.py, we get the undesired behavior.
Is there any way to make %run behave like the command line here? This seems like a real deficiency with using ipython as a testing environment for scripts. (Or perhaps the moral is that a module shouldn't be writing into another module's namespace?)
Upvotes: 18
Views: 8048
Reputation: 930
I am encountering the same problem. It seems to me this is an undesirable effect of ipython's run command - it doesn't reload imported modules.
The author is right: If changes have been made to ex2.py, the following command will help reload
%load_ext autoreload
%autoreload 2
My simplest way to get around is to modify the imported modules (in this example, ex2.py) each time, and execute the following commands in ipython
%load_ext autoreload
%autoreload 2
%run ex1.py
This helps reload ex2.py.
Note that ex2.py has to be modified every time before you execute the 3 lines above. It is only by this way module ex2 can be reloaded.
Upvotes: 6
Reputation: 36506
%run ex1.py
(or any script for that matter) does not do deep reload of your imported module even with the autoreload extension set to 2. It is a "flaw" with how the %run
command works in ipython.
You will have to explicitly call
dreload(ex2)
for a deep reload before executing %run ex1.py
again.
See - http://ipython.org/ipython-doc/dev/api/generated/IPython.lib.deepreload.html
There might be plans to make %run
do deep reload automatically in future and you can find this issue, which is still an open issue at this time of writing, being suggested by a user here - https://github.com/ipython/ipython/issues/461
Upvotes: 11