How to do code formatting in jupyter notebooks?

I am used to formatting my code using black and isort with normal python scripts. I have been slowly using jupyter notebooks as a development tool. I am curious to know how can I format using black in jupyter notebooks?

On a quick google search, I found this tool: Code Formatting Jupyter Notebooks with Black : Coiled

Yet with cloud providers like google colab, JarvisLabs.ai it looks not possible. Can anyone suggest some good alternatives?

pip install black[jupyter]

1 Like

And how to apply across all the cells? Is it to be done using black-cli itself @miwojc ?

like: black -m app.ipynb

1 Like

This explains a way that probably would do what you want, I think.

You could also consider just opening your notebooks inside VSCode. I know they’ve been working hard to give a notebook experience that matches the original…

2 Likes

Yes just as any other py file

1 Like

Thanks for sharing these approaches @miwojc and @strickvl :pray:

2 Likes

The best way I found is a Jupyter Notebook Extension called Autopep8. It adds a button to format the selected cell.

Here is a nice blog post in case you don’t know much about Jupyter Notebook Extensions:
https://towardsdatascience.com/jupyter-notebook-extensions-517fa69d2231

Once you have that, you can add loads of very very useful extensions like the Autopep8.

3 Likes

In VSCode you can simply right click a cell and select “format cell” or “format notebook”. You can configure what formatter you want to use.

I use black myself across the board for all python and I find it a) the most standard and b) of the standard formats, the most readable.

As an aside, I code my notebooks in VSCode about 99% of the time these days.

4 Likes