I agree that this is often a preferred approach! I always have my notebooks configured to work like that because it:
- makes it easy to specify paths to data and for outputs and
- allows moving a notebook between directories without the need to change the paths
- makes jupyterlab-lsp code intelligence work more reliably
I have a python module called make_paths_absolute.py
with the following contents:
from os import chdir
from pathlib import Path
def make_paths_relative_to_root():
"""Always use the same, absolute (relative to root) paths
which makes moving the notebooks around easier.
"""
top_level = Path(__file__).parent
chdir(top_level)
make_paths_relative_to_root()
And in the first cell of every notebook, I add a line import make_paths_absolute
. I like it this way because it makes it:
- reproducible: anyone who copies/clones my project will be able to run the code without the need to customize anything in their Jupyter environment
- work with all notebook interfaces (whether JupyterLab/RetroLab/classic Notebook)
- is quite obvious for anyone reading the notebook that they should expect the paths to be absolute (=relative to the root).
To make that work you first need to set PYTHONPATH
pointing to the root of the repository when starting JupyterLab. To do so on Linux/Mac you can prepend the jupyter lab command with:
PYTHONPATH=/path/to/your/lab/root:$PYTHONPATH jupyter lab
Alternatively, you can specify PYTHONPATH
in kernel.json
(either by modifying the default kernel specification or creating a copy of it first, see https://stackoverflow.com/a/53595397).
PS. The above is a simplification of my setup. In reality, I store make_paths_absolute.py
in helpers
package (so there is also an empty helpers/__init__.py
and there is extra .parent
) together with other initialization-time code, including a notebook called notebook_setup.ipynb
which contains things like %matplotlib inline
, pandas customizations (like making sure it uses stable sort), warning filters etc. So my every notebook starts with:
import helpers.make_paths_absolute
%run helpers/notebook_setup.ipynb
and I am really liking this setup working like that for two years now without any problems.
There is a feature request for making this easier at: https://github.com/jupyterlab/jupyterlab/issues/11619.