Skip to content

Instantly share code, notes, and snippets.

@chongshenng
Created November 3, 2022 15:41
Show Gist options
  • Select an option

  • Save chongshenng/c8a7008c48957a347e750ae0fc5a575b to your computer and use it in GitHub Desktop.

Select an option

Save chongshenng/c8a7008c48957a347e750ae0fc5a575b to your computer and use it in GitHub Desktop.
Sometimes you need relative imports in a notebook ...

Given this directory structure

project
├── utils
│   └── module.py
└── notebooks
    └── notebook.ipynb

and that you want to import module.py in notebook.ipynb. Add the directory path to the notebook like so,

import os, sys
directory_path = os.path.abspath(os.path.join('..'))
if directory_path not in sys.path:
    sys.path.append(directory_path)

And then from within notebook.ipynb you can import module.py like so:

from utils.module import my_func

This address the issue of ImportError: attempted relative import with no known parent package found when running notebooks. Ref:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment