Code formatter like nb_black for google colab

Solution 1:

I don't think there's an extension directly in Colab.

What you could do, though, is to download your notebook, run

pip install -U nbqa
nbqa black notebook.ipynb

and then reupload your (now formatted) notebook to Colab


disclaimer: I'm the author of nbQA


UPDATE: as of version 21.8b0, black runs directly on notebooks, no third-party tool required

Solution 2:

I have tried everything, none of the JupyterLab/Notebook backend hack methods seem to work as of February 2022. However, until later here is a relatively simple workaround:

[Run only once, at startup]

  • Connect to your drive

    from google.colab import drive
    drive.mount("/content/drive")

  • Install black for jupyter

    !pip install black[jupyter]

  • Restart kernel

[Then]

  • Place your .ipynb file somewhere on your drive
  • Anytime you want format your code run:
    !black /content/drive/MyDrive/YOUR_PATH/YOUR_NOTEBOOK.ipynb
  • Don't save your notebook, hit F5 to refresh the page
  • Voila!
  • Now save!