Setup JupyterLab the right way

While JupyterLab comes with default python kernel, we often want to create a virtual environment for each notebook, and register the virtual environment as a kernel for JupyterLab.

Use pyenv to manage the local Python versions

Using pyenv to manage the local Python versions

pyenv versions
  system
* 3.11.3 (set by /Users/username/.pyenv/version)

Install jupyterlab

Following this guide: https://jupyter.org/install, installing JupyterLab with pip

# Install JupyterLab with pip:
pip install jupyterlab
# launch JupyterLab
jupyter lab

Manage kernels

Usually there is a default kernel created, which is pointing to the Python set with pyenv

> jupyter kernelspec list
0.00s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
Available kernels:
  python3    /Users/username/.pyenv/versions/3.11.3/share/jupyter/kernels/python3

Keep the notebook in a specific folder that is also a git repo, so I can have an isolated environment for each set of notebooks. Following this guide

Create and activate a virtual environment:

python -m venv .venv
. .venv/bin/activate

To deactivate the virtual environment, run:

deactivate

Install ipykernel in the virtual environment:

python -m pip install ipykernel

Register the virtual environment as a Jupyter kernel:

python -m ipykernel install --name {MACHINE_NAME} --display-name "{DISPLAY_NAME}" --user

example:

python -m ipykernel install --name my-lab --display-name "Python 3.11.3" --user

Check the kernels, we now have a new kernel created specifically for this virtual environment in this folder

jupyter kernelspec list
  0.00s - Debugger warning: It seems that frozen modules are being used, which may
  0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
  0.00s - to python to disable frozen modules.
  0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
  Available kernels:
    my_lab     /Users/username/Library/Jupyter/kernels/my_lab
    python3    /Users/username/.pyenv/versions/3.11.3/share/jupyter/kernels/python3

Launch JupyterLab

jupyter lab
jupyterlab
The custom kernel is now available in JupyterLab
jupyter notebook
Any packages installed in the notebook will be located in this virtual environment