Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reload Python module within Jupyter notebook (without autoreload)

I have the following folder structure

project/
  src/
    __init__.py
    mymodule.py
  mynotebook.ipynb

within mynotebook I can import mymodule using standar formula from src.mymodule import *. The problem pops up when modifying mymodule and trying to reimport it without stopping the kernel. I am following this discussion but it is not working. (python ver: 3.3.5)

from imp import reload 
reload(src.mymodule) # also reload(mymodule)

the code above fails with message name 'src' is not defined (also name 'mymodule' is not defined). I can't use ipython's autoreload because I have no permissions to install it.

Thanks!

like image 542
lsmor Avatar asked Sep 19 '18 07:09

lsmor


2 Answers

You need to import src too and then reload(src.mymodule).

from src import mymodule
import src
# Change in mymodule
reload(src.mymodule)
like image 92
kada Avatar answered Sep 28 '22 09:09

kada


This embellishes James Owers's comment from the Python3 documentation @ https://docs.python.org/3/library/importlib.html

This is my module import, when I edit the model I need to reload it.

import src.project.model as Mdl

This gives us the reload function

from importlib import reload

.. and when you want to reload your module in a cell

reload(Mdl)

like image 34
Kickaha Avatar answered Sep 28 '22 09:09

Kickaha