diff --git a/docs/index.rst b/docs/index.rst index eb7548b..051a9b1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -79,6 +79,21 @@ If you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ``ipynb.fs.defs`` instead of ``ipynb.fs.full``. Full uppercase variable assignment will get evaluated as well. +Relative imports +================ + +If you want to import notebooks from other notebooks relatively, you can easily +do that with the following: + +``` +import ipynb.fs +from .full.notebook1 import foo +from .defs.notebook2 import bar +``` + +This will do the imports from other notebooks relative to the path of the notebook +in which the importing is happening. The `import ipynb.fs` is boilerplate that is +required for this feature to work properly. Releasing a package that contains notebook files ================================================ diff --git a/ipynb/fs/__init__.py b/ipynb/fs/__init__.py index e69de29..a399eb9 100644 --- a/ipynb/fs/__init__.py +++ b/ipynb/fs/__init__.py @@ -0,0 +1,32 @@ +""" +Module to enable relative & absolute import of .ipynb files. + +This file in particular is useful to enable relative imports in +interactive notebook usage. None of the code executes outside +of an interactive notebook environment. + +Relative imports require two things: + - `__package__` is set + - The module that is `__package__` is already imported + +So we set __package__ in the notebook's namespace to the __package__ +of this variable. This will allow users to do imports like: + +``` +from .full.notebook1 import foo +from .defs.notebook2 import bar +``` + +and they would work everywhere just fine. +""" +try: + import IPython + ip = IPython.get_ipython() + + if ip is not None: + if ip.user_ns['__package__'] is None: + ip.user_ns['__package__'] = __package__ +except ImportError: + # If we don't have IPython installed at all, let it go. + # We aren't running in a jupyter notebook then. + pass