TL;DR: I show you how to get simply pretty code in Jupyter notebooks AND Jupyter Lab.
If you are using exclusively Jupyterlab, I now recommend using this extension, because one does not need to use jupyter %magics anymore, which makes cleaner notebooks: https://jupyterlab-code-formatter.readthedocs.io/en/latest/index.html
Another advantage of that extension is, that it supports 4 different code formatters (black, yapf, autopep8, isort)
If you have installed an older version of
nb_black , do an update (
pip install -U nb_black), because some of the recent updates were quite helpful, e.g. adding compatibility with jupyter %magics.
Are you too busy to make code look pretty (i.e. “readable”) while developing it in Jupyter notebooks? Here’s something you might be interested in.
One of the Python core devs, Łukasz Langa, has developed a Python code formatter a while ago called Black. He calls it “the uncompromising code formatter”. What he means is, that code has “opinions” on how code should look like, but maybe you simply don’t care precisely, you just want it done efficiently, so that you can get on with your work. (I paraphrase). I like this idea, because discussing the merits of how precisely code should be aligned can be … challenging, for the lack of a better word.
Now, my current favorite editor VSCode (free, open source) has nice Python linting (i.e. code evaluation) enabled via different code linters and reformatters. So, you can simply enable
black in there (search the settings via “python.linting.black”). But this is about Jupyter notebooks and labs.
Install Jupyter plugin and use
I just found this little wrapper around a small formatting function using
black , it’s called
nb_black. Here’s how you install it:
First, you install the black library using
conda from the conda-forge channel:
conda install -c conda-forge black
Now you add the
nb_black package via
pip install nb_black
and to use it in Jupyter notebooks, you add this to the first cell of a notebook:
while for Jupyter Lab you add this to the first cell of a notebook:
Done. To use it, simply execute a cell as usual. And if you are tired of it or need it to stop doing its thing for a while, simply reload the notebook and skip executing the first cell. I think this is a convenient enough way to get pretty code cells until we get a button up there to switch it on and off. I’ll update this post if I hear anything about that.