Shaharg
Shaharg

Reputation: 1029

Pycharm: how to refresh Jupyter after changing the code of an imported module

I am using a Jupyter notebook in Pycharm and from time to time I update external modules imported by the notebook. For some reason, the kernel ignores my recent changes and behaves as if the code wasn't changed. My current workaround is to stop and restart the Jupyter server but this seems like an overkill. Another thing that might be connected is a warning I get "Notebook kernel doesn't match Project interpreter"

Did anyone encounter a similar problem and knows how to solve it?

Upvotes: 6

Views: 1236

Answers (3)

Maple38
Maple38

Reputation: 1

Add this to any cell, ideally one already used for imports or a brand new cell.

%load_ext autoreload
%aimport thing_to_reload
%autoreload 1

Here's a breakdown:

%load_ext autoreload loads the autoreload extension into Jupyter.

  • %aimport thing_to_reload is just a regular import but with %a added on, to mark it for reloading.
  • %autoreload 1 just tells Jupyter to autoreload in mode 1.

Mode 1 only reloads things you explicitly mark with %aimport, I prefer this to the mode 2 that others may suggest. Additionally, in mode 2, you may use %aimport -thing_to_reload to explicitly exclude things from reloading.

Upvotes: 0

MjH
MjH

Reputation: 1570

I recommend using IPython autoreload extension - link. Just add the following in your import a separate cell:

%load_ext autoreload
%autoreload 2

There are different autoreload options. 2 is to reload all modules every time before you use them.

Upvotes: 4

Hypatia
Hypatia

Reputation: 49

This fixed the issue for me:

import importlib
importlib.reload(name_of_your_module)

before you use functions from that module on your notebook.

Upvotes: 1

Related Questions