Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to reload my kernel everytime I add a new function?

So, I am developing a Python package, and the way I am doing it is, I test the functions in my notebook and then offload them to functions.py etc.

/testpack/
    __init.py__
    functions.py
    plotting.py
/notebooks/
    plottingnotebook.ipynb

And I have this in my notebook:

# Project package
module_path = os.path.abspath(os.path.join('../'))
if module_path not in sys.path:
    sys.path.append(module_path)
import testpack as tp # Import project package

But when I add a new function or make changes to existing one in functions.py for example, and reimport in the notebook, these functions are not available to use.

However, this works when I restart the kernel in the notebook.

Is this expected behavior? If not, how can I make sure the changes I make can be imported without having to restart the kernel?

like image 357
maximusdooku Avatar asked Oct 28 '25 06:10

maximusdooku


1 Answers

Python thinks you've already imported the module so it skips it. You can force python to re-import a module by using the builtin reload function found in importlib. Note that reload will raise NameError if the module has not been imported yet. A scheme like this should work

try:
    import importlib
    importlib.reload(tp)
except NameError: # It hasn't been imported yet
    import testpack as tp
like image 167
SyntaxVoid supports Monica Avatar answered Oct 31 '25 03:10

SyntaxVoid supports Monica