google-colaboratorypep8python-black

Code formatter like nb_black for google colab


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)?


Solution

  • 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.
    

    :-)