[Tutor] Importing functions in IPython

Steven D'Aprano steve at pearwood.info
Sun Jan 22 23:39:57 CET 2012

On Mon, Jan 23, 2012 at 03:40:26AM +0530, Jaidev Deshpande wrote:
> Dear List,
> Suppose I have a function myfunc() in a module called mymodule.py
> Now when I delete the original function and import the changed one,
> In[2]: del myfunc
> In[3]: from mymodule import myfunc
> it doesn't work as per the new changes. I have to close IPython and
> start all over again.

As far as I know, this is not an IPython specific problem, but is due to 
the way Python imports modules.

Here are two alternatives:

1) Instead of "from mymodule import myfunc", instead use 

import mymodule
result = mymodule.myfunc()  # not myfunc() on its own

After changing the source file, do "reload(mymodule)" and Python will 
pick up the changes.

2) You can manually force a reload:

import sys
del sys.modules['mymodule']
from mymodule import myfunc

But two warnings:

* reload() is very simple-minded. It is not guaranteed to change the 
behaviour of existing objects just because the module is reloaded. The 
most common example of this is if you use classes: reloading the module 
after modifying the class will NOT change the behaviour of any existing 
instances. E.g.:

import mymodule
instance = mymodule.MyClass()
# now edit MyClass in mymodule and change the method behaviour
instance.method()  # instance will keep the OLD behaviour, not the new

* Because reload() so often doesn't work as expected, in Python 3, it 
has been removed from the built-ins and is now found in the imp module.


More information about the Tutor mailing list