anthe.sevenants

Reloading CLASSES using IPython %autoreload

2022-04-04

If you're working with a Jupyter Notebook while at the same time developing some sort of external library, it might be interesting to reload these external libraries without having to restart the entire kernel of your notebook. If you look on the internet, you might believe that the following two "magic" commands are enough:

%load_ext autoreload
%autoreload 2

This is true if you're only importing modules. However, if you only import classes from these modules, the autoreload code won't work. For example, if you import the classes ModelCollection and Model directly from the module nepho_nn, autoreload won't detect any changes in the source code for these classes.

from nepho_nn.model_collection import ModelCollection
from nepho_nn.model import Model

The trick to solve this issue is to first implement the module itself (nepho_nn in the example). Once you've imported the module itself, autoreload will find it, and your classes will now also update if you change their code.

# Solution: import "nepho_nn" first
import nepho_nn
from nepho_nn.model_collection import ModelCollection
from nepho_nn.model import Model