How to do manual reload of file in iPython shell
<p>I have a file called sub.py, and I want to be able to call functions in it from the iPython shell. The iPython autoreload functionality has not been working very well, though. Sometimes it detects changes, sometimes it doesn't. </p>

<p>Instead of debugging autoreload, I was wondering if there's a way to just manually reload, or unload and load, modules in iPython. Currently I terminate the shell, start it again, re-import my module, and go from there. It would be great to be able to do a manual reload without killing the iPython shell. </p>

<p>I find my homebrewed <code>%reimport</code> to be very useful in this context:</p>

<pre><code>def makemagic(f):
    name = f.__name__
    if name.startswith('magic_'): name = name[6:]
    def wrapped(throwaway, *pargs, **kwargs): return f(*pargs,**kwargs)
    if hasattr(f, '__doc__'): wrapped.__doc__ = f.__doc__
    get_ipython().define_magic(name, wrapped)
    return f

@makemagic
def magic_reimport(dd):
    """
    The syntax

        %reimport foo, bar.*

    is a shortcut for the following:

        import foo; foo = reload(foo)
        import bar; bar = reload(bar); from bar import *
    """
    ipython = get_ipython().user_ns
    for d in dd.replace(',', ' ').split(' '):
        if len(d):
            bare = d.endswith('.*')
            if bare: d = d[:-2]
            exec('import xx; xx = reload(xx)'.replace('xx', d), ipython)
            if bare: exec('from xx import *'.replace('xx', d), ipython)
</code></pre>

<p>Once gotcha is that, when there are sub-modules of packages involved, you have to <code>reimport</code> the sub-module, and <em>then</em> the top-level package:</p>

<pre><code>reimport foo.bar, foo
</code></pre>

python ipython