Post

Relative-import error when using jupyter notebook

This article introduces a solution to the relative-import error when using the jupyter notebook.

The annoying relative-import error

The annoying relative-import error frequently occurs when using python.

1
ImportError: attempted relative import with no known parent package

When using jupyter notebook, solving it becomes harder because two commonly known solutions doesn’t apply.

1
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

or

1
python -m relative.modules

Specifically, this is because you can’t access to __file__ nor pass the -m argument when executing.ipynb files with jupyter notebook.

Solution for the issue

After some workarounds, I found a new solution for the issue. Instead of passing -m, you can add the following lines at the top of each .ipynb file.

1
2
3
4
if __package__ is None:
    # Set the top level package
    # Analogus to python -m relative.modules
    __package__ = 'relative.modules'

This will enable you to use relative imports such as:

1
2
from . import *
from .. import utils
This post is licensed under CC BY 4.0 by the author.