Skip to content

activating relative imports in an interactive notebook¤

%%
<details>
<summary>
        make a directory called <var>relative</var> to demonstrate permitting relative imports in notebooks
    </summary>

    !mkdir relative -p
    !touch relative/script.py
    !touch relative/__init__.py

</details>
make a directory called relative to demonstrate permitting relative imports in notebooks
!mkdir relative -p
!touch relative/script.py
!touch relative/__init__.py
%%
normally when we encounter an `ImportError` if we attempt to use a relative import
in an interative notebook

    &gt;&gt;&gt; from .relative import script
    Traceback (most recent call last):
      ...
    ImportError: attempted relative import with no known parent package

normally when we encounter an ImportError if we attempt to use a relative import in an interative notebook

    >>> from .relative import script
    Traceback (most recent call last):
      ...
    ImportError: attempted relative import with no known parent package
%%
we can make the interactive shell imitate a package that would have relative imports
by including `__path__` and `__package__` variables. 

    __path__, __package__ = [""], "__main__"

the statement above unlocks relative imports, and we don't fail the following statements.

    &gt;&gt;&gt; from .relative import script
    &gt;&gt;&gt; script
    <module '__main__.relative.script'="" ...="" from="">

we can make the interactive shell imitate a package that would have relative imports by including __path__ and __package__ variables.

__path__, __package__ = [""], "__main__"

the statement above unlocks relative imports, and we don't fail the following statements.

    >>> from .relative import script
    >>> script
    <module '__main__.relative.script' from ...>

conclusion¤

  • set the __path__ and __package__ to enjoy a more flexible programming experience.
  • using relative importants makes it easier to include notebook content in python packages.