Skip to content
Advertisement

ImportError: cannot import name ‘MyClass’ from “myFile.py”, without restarting the notebook

Using VSCode, I have a file myFile.py with a class myClass

# myFile.py
class myClass(nn.Module):
    def __init__(self):
         super(myClass, self).__init__())
         self.a = 1

No in a JupyterNotebook someNb.ipynb inside the same folder as myFile.py I just want to import myClass in a python cell:

from myFile import myClass

However, even though I am saving both files (as stated in other questions), I get the following error:

ImportError: cannot import name 'myClass' from 'myFile' (<path-to-myFile.py>) 

I also tried to add

%load_ext autoreload
%autoreload 24

before from myFile import myClass, but also this does not see the changes in myFile.py.

Note: When I reopen the notebook it works. And <path-to-myFile.py> is the correct path.

So the issue is more: Why do I need to reopen the whole notebook everytime I am making changes to myFile.py? I just want to make changes to myFile.py, save both someNb.ipynb and myFile.py, and import the new changes (classes), without reloading the notebook and loosing all variables.

Advertisement

Answer

According to the explanation here, this is the mechanism of jupyter.

If it is modified in an external file (such as a python file), the change will not be recognized in jupyter. Because this module is already imported after opening jupyter for the first time and running the code, the interpreter kernel already exists this module.

So if you want the jupyter kernel to notice the change, you have to restart jupyter.

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement