0

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.

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.

CAJ
  • 297
  • 1
  • 3
  • 12
  • Don't answers from that question help you? http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module – skovorodkin Oct 03 '16 at 17:02
  • I wonder if your troubles with ipython reload could be due to .pyc files hanging around. Try and put the environment variable `export PYTHONDONTWRITEBYTECODE=1` and see if it alleviates matters. – wim Oct 03 '16 at 17:03

1 Answers1

1

I find my homebrewed %reimport to be very useful in this context:

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)

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

reimport foo.bar, foo
jez
  • 14,867
  • 5
  • 37
  • 64