Michael Dorner
Michael Dorner

Reputation: 20185

Import local modules in Jupyter notebook

I would like to outsource some general functions useful for multiple notebooks in a module (also for testing purposes). The current directory structure looks like the following

jupyter/
├─ notebooks/
│  ├─ 01 Notebook 1.ipynb
│  ├─ ...
├─ src/
│  ├─ module_a/
│  │  ├─ __init__.py
│  │  ├─ func_a.py
│  ├─ module_b/...
├─ tests/...
├─ data/...
├─ .../

In func_a.py, there is a simple function def print_a(): print('a')

However, when I would like to import and use module_a in 01 Notebook 1.ipynb by using (what I think makes sense)

from .. src.module_a import print_a

I got an ImportError: attempted relative import with no known parent package. What am I doing wrong? I am using Python 3.9.

Upvotes: 1

Views: 7103

Answers (1)

Dr. Prof. Patrick
Dr. Prof. Patrick

Reputation: 1374

I would try to append the src directory to the system path like so:

import sys
sys.path.append("/path/to/your/src")

from src.module_a import a

please note that you can use the relative path from your notebook root and not absolute path like in the example above, so the following:

sys.path.append("src")

should work too

Upvotes: 4

Related Questions