2

I have written simple class called CombinedAttributesAdder in the same directory where my .ipynb file is. Like:

-project
 -project.ipynb
 -combined_attributes_adder.py

This file contains class called CombinedAttributesAdder When I try to import this class into ipynb like:

from combined_attributes_adder import CombinedAttributesAdder

it gives me an error:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-73-65ed70439bcc> in <module>
----> 1 from combined_attributes_adder import CombinedAttributesAdder

ImportError: cannot import name 'CombinedAttributesAdder' from 'combined_attributes_adder' (/home/mat/Documents/Projects/machine-learning-notebooks/projects/combined_attributes_adder.py)

why is that?

Mateusz Gebroski
  • 1,274
  • 3
  • 26
  • 57

1 Answers1

1

There can be multiple reasons for this. The one I found when I encountered the same error was that Jupyter does not seem to re-read the Python file after it has already been imported once.

So, if you do an initial import with:

import combined_attributes_adder

then add the class CombinedAttributesAdder to combined_attributes_adder.py, change your cell to the following and re-run the cell without restarting the kernel, you get exactly the error message you posted:

from combined_attributes_adder import CombinedAttributesAdder

After a change in the imported Python file you may have to restart the kernel in order to pick up the changes if you imported the module before already.

To avoid this you may use the 'run' magic instead, as shown in this answer:

%run -i 'combined_attributes_adder.py'

Which essentially acts the same as

from combined_attributes_adder import *

The linked answer also contains a way to auto-reload on change.

dev-zero
  • 81
  • 1
  • 9