Reloading imports in Jupyter Notebooks
Python
Jupyter
Little Tricks
This is another short post mostly written for me to remember something. When working on a Python library, I like to have a Jupyter Notebook for testing. However, by default, a Jupyter Notebook only runs every import once. So any imported module that’s actively being developed remains in the state in which it was first loaded until a forced reload.
One way to do a forced reload is to restart the kernel. But this is often inconvenient. A more convenient way is to use the importlib
module as follows:
# import the importlib library first
import importlib
# next import your module
import my_module
# force the module to reload each time the cell runs
reload(my_module)
importlib.# only now laod specific functions from that the module
from my_module import some_function
Important: Even if you only want the last line of code, you have to include the first four (ignoring comments). Reloading individual functions does not work this way, that is, importlib.reload(some_function)
produces an error.