4

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?

maximusdooku
  • 5,242
  • 10
  • 54
  • 94

1 Answers1

2

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
SyntaxVoid
  • 2,501
  • 2
  • 15
  • 23
  • Thanks! And what about `import testpack as tp`? Should I keep it or remove it? – maximusdooku Apr 24 '19 at 20:17
  • Should this happen before or after `import testpack as tp`. And if this part is not required, how can I tell it to reload as `tp`? Am I understanding this wrong? – maximusdooku Apr 24 '19 at 20:21