Jupyter notebook fails to connect to kernel due to module name conflict

Viewed 22

I had the following folder structure for a python ML project:

├── root
   ├── code
   │   ├── foo.py
   │   └── bar.py
   ├── notebook.ipynb
   ├── foo
   └── bar

After writing the two .py files in the code folder, I tried to run the two files but had some errors similar to this:

ModuleNotFoundError: No module named 'code.foo'; 'code' is not a package

This was caused by imports along the lines of this:

from code.foo import x

I tried searching for a solution and found out that adding an empty __init.py__ file would help "having python know my folder was a module" (sorry for the bland description, I can't remember the technicalities). In fact, I had no such errors since. New hierarchy looks like this:

├── root
   ├── code
   │   ├── __init__.py
   │   ├── foo.py
   │   └── bar.py
   ├── notebook.ipynb
   ├── foo
   └── bar

Unfortunately, as I tried opening notebook.ipynb with Jupyter Notebook, this failed to connect to the kernel, showing this error in the command prompt:

i.e.: the module "code" could not be imported because it is shadowed by:
...\root\code\__init__.py
Please rename this file/folder so that the original module from the standard library can be imported.

I could delete/rename the __init.py__ file everytime I need to use the notebook, but that's not very efficient in terms of workflow. Is there any solution to this conflict? As I stated I have no necessity of keeping the __init.py__ file, if that information helps.

Thanks for the attention!

2 Answers

Your problem is that there is already a package named code in python. So your new package is shadowing the original code package. Change the name to myPackage for example and it should be fine.

The init.py files are mandatory for python to identify the folder as a package, you need to keep it.

To use this package you can use import code

and while using you can write code.x

else you can use from foo import * or import foo will work also

Related