Enable code folding in JupyterLab

1 minute read see also comments

Code folding is a quite useful solution, e.g., to enhance the visibility of scripts with large amounts of code. It allows to view only those parts of the script that are currently of interest.

img Enabled code folding in JupyterLab. Left: Unfolded text. Right: Folded text.

How to enable code folding in JupyterLab

Code folding in JupyterLab can be enabled in the JSON Settings Editor. To do so, choose from the menu bar Settings->Advanced Settings Editor, and in the then opened Settings tab, click on JSON Settings Editor in the upper right corner:

img JupyterLab’s Advanced Settings Editor. Open the JSON Settings Editor by clicking on the button in the upper right corner.

In the JSON Settings Editor, click in the left panel on Notebook. In the corresponding editor window User Preferences (the rightmost window) type CMD+f/Ctrl+f and search for “codeFolding”:

img JupyterLab’s JSON Settings Editor. Having the Notebook tab activated, search for “codeFolding” in the User Preferences window.

Replace in all occurring codeFolding settings false by true:

img Change the codeFolding setting from false to true.

This enables code folding in Jupyter notebooks. To enable code folding in pure Python scripts as well, repeat these steps also in the Text Editor tab.

Code folding in action

In Jupyter notebooks, code folding looks like:

img img A Jupyter notebook in JupyterLab. Top: Unfolded text. Bottom: Folded text.

And in pure Python scripts:

img img A pure Python script in JupyterLab: Top: Unfolded text. Bottom: Folded text.

What can be folded?

We can fold all default Python code blocks like functions, for-loops, if-blocks, or classes. Unlike other editors and IDE like PyCharm, Spyder or VS Code, we are, however, not (yet) able to fold code cells (initialized by # %%), which would further enhance the visibility of long code scripts. Maybe this will be possible in a future version of JupyterLab.

img img Pure Python script in VS Code. Top: Unfolded text. Bottom: Folded text. Note, that we can also fold code cells (initialized by # %%) here.

comments