Code formatter like nb_black for google colab
Asked Answered
L

3

59

I know that for jupyter notebooks and jupyter lab, there are available code formatter extensions such as nb_blackor blackcellmagic. However when I installed them, it doesn't seem to work on google colab.

Do you know if there are any native option in colab or an extension that formats code (pep8 compliant)?

Lucas answered 24/7, 2020 at 14:47 Comment(0)
E
12

As of now (April 2023) the top answer - black - works without kernel restarts.

So

# run once
!pip install black[jupyter] --quiet
from google.colab import drive
drive.mount("/content/drive")
...
# run many times
!black /content/drive/MyDrive/'Colab Notebooks'/'HiringBias.ipynb'

plus page refreshing gives

reformatted /content/drive/MyDrive/Colab Notebooks/HiringBias.ipynb
All done! ✨ 🍰 ✨
1 file reformatted.

:-)

Escapism answered 16/4, 2023 at 20:56 Comment(0)
M
14

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

Marjorie answered 14/7, 2021 at 10:44 Comment(0)
G
13

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!
Geter answered 5/2, 2022 at 19:3 Comment(1)
+1 It was great. I needed slight modification (!black '/content/drive/MyDrive/YOUR_PATH/YOUR_NOTEBOOK.ipynb') as my path contained a folder that had a space in its name.Laevogyrate
E
12

As of now (April 2023) the top answer - black - works without kernel restarts.

So

# run once
!pip install black[jupyter] --quiet
from google.colab import drive
drive.mount("/content/drive")
...
# run many times
!black /content/drive/MyDrive/'Colab Notebooks'/'HiringBias.ipynb'

plus page refreshing gives

reformatted /content/drive/MyDrive/Colab Notebooks/HiringBias.ipynb
All done! ✨ 🍰 ✨
1 file reformatted.

:-)

Escapism answered 16/4, 2023 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.