I was looking to auto format my notebooks with Black
I found a couple such as
However, they were all missing features, were out of date, and had issues.
Writing my own version would have been 2 short files, however, I found that code_prettify is so extensible that you can easily configure it to use Black using the nbextensions configurable parameters.
Features (and issues solved)
- skip jupyter magic lines
- configurable shortcuts
- adds a toolbar button
- runs for all selected cells
- can format whole notebook
- don’t have to run the cells
- don’t have to load ext each notebook
- don’t have to add notebook magics to each cell
- allowing for the cells to be edited while running
- deal with Black’s changing API and works with the most recent Black version, as well as previous ones
- works with the most recent jupyter version
The python code I’ve written to do the black formatting is:
def black_reformat(cell_text): import black import re cell_text = re.sub("^%", "#%#", cell_text, flags=re.M) try: reformated_text = black.format_str(cell_text, 88) except TypeError: reformated_text = black.format_str( cell_text, mode=black.FileMode(line_length=88) ) return re.sub("^#%#", "%", reformated_text, flags=re.M)
- go to your Nbextensions in your jupyter notebook
- to install nbextensions see https://github.com/ipython-contrib/jupyter_contrib_nbextensions#1-install-the-python-package
- enable Code prettify
- paste above json into text box labeled
json defining library calls required to load the kernel-specific prettifying modules, and the prefix & postfix for the json-format string required to make the prettifying call.
This also requires black to be installed in the running kernel and it therefore goes without saying this only works in py>=3.6