Yes, I know this is a recurrent question but I still couldn't find a convincing answer. I even read at https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html but could not find out how to solve the problem:
I'm running python 3.6 project that includes jupyter (ipython) notebooks. I want the notebook to import a custom local helpers.py
package that I will probably use also later in other sources.
The project structure is similar to:
my_project/ │ ├── my_project/ │ ├── notebooks/ │ └── a_notebook.ipynb │ ├── __init__.py # suppose to make package `my_project` importable │ └── helpers.py │ ├── tests/ │ └── helpers_tests.py │ ├── .gitignore ├── LICENSE ├── README.md ├── requirements.txt └── setup.py
When importing helpers
in the notebook I get the error:
----> 4 import helpers ModuleNotFoundError: No module named 'helpers'
I also tried from my_project import helpers
and I get the same error ModuleNotFoundError: No module named 'my_project'
I finally (and temporarily) used the usual trick:
import sys sys.path.append('..') import helpers
But it looks awful and I'm still looking for a better solution
A module can be imported into an interactive console environment (e.g. a Jupyter notebook) or into another module. Importing a module executes that module's code and produces a module-type object instance. Any variables that were assigned during the import are bound as attributes to that object.
One can tell python where to look for modules via sys.path
. I have a project structure like this:
project/ │ ├── src/ │ └── my_module/ │ ├── __init__.py │ └── helpers.py ├── notebooks/ │ └── a_notebook.ipynb ...
I was able to load the module like so:
import sys sys.path.append('../src/') from my_module import helpers
One should be able load the module from wherever they have it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With