Search code examples
pythonjupyter-notebook

How to refresh a Python import in a Jupyter Notebook cell?


I have two files:

MyModule.py MyNotebook.ipynb

I am using Jupyter Notebook, latest, and Python, latest. I have two code cells in my Notebook.

Cell #1

import some stuff
Run some code
(Keep everything in the environment takes about five minutes to run this cell).

Cell #2

import MyModule
Execute code from MyModule

I would like to make code changes in MyModule.py and rerun Cell #2 but without restarting the kernel (Cell #1 did a fair amount of work which I don't want to rerun each time). If I simply run the second cell, those changes made to MyModule.py do not propagate through. I did some digging, and I tried using importlib.reload. The actual code for Cell #2 :

from Nash.IOEngineNash import *
import importlib
importlib.reload(Nash.IOEngineNash)

Unfortunately, this does not work, because repeat running of an import statement in a Jupyter notebook has no effect. How can I push those changes in MyModule.py (or Nash/IOEngineNash.py in actual fact) into my Notebook without restarting the kernel and running from scratch?


Solution

  • I faced a similar issue , while importing a custom script in jupyter notebook

    Try importing the module as an alias then reloading it

    
    import Nash as nash
    from importlib import reload
    reload(nash)