reloading module which has been imported to another module

J-bob picture J-bob · Dec 24, 2012 · Viewed 9.8k times · Source

Let's face it, the whole business of reloading python code after changing it is a mess. I figured out awhile back that calling import <module> at the interpreter is better than from <module> import <class/function>, because then I can call reload(module) to get updated code.

But I have more complicated issues now. So I have this file, module1.py, and at the top it says:

from module2 import <class1>, <function1>, etc.

And then I go and change code inside module2. Turns out that calling reload(module1) will not reload the code changed in module2, even though code from module2 is imported at the top of module1. Is there any way to reload everything without restarting the interpreter?

Before anyone gets on my case about style, I'll just say that:

  1. I only call reload from the interpreter, never in active code. This question concerns when I'm testing new code.
  2. I never call from <module> import *, I know that destroys readability

Answer

ojdo picture ojdo · Jun 28, 2013

Have a look into IPython. It has the autoreload extension that automatically reloads modules during the interpreter session before calling functions within. I cite the example from the landing page:

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43