Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support relative imports from inside notebooks #24

Merged
merged 1 commit into from
Nov 14, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
================================================
Expand Down
32 changes: 32 additions & 0 deletions ipynb/fs/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Let it go", let it go ...

# We aren't running in a jupyter notebook then.
pass