Use the Code Prettify Jupyter Extension

Background image by Free-Photos from Pixabay

Sometimes when writing code in a Jupyter notebook, you may be in a hurry and don’t want to spend time on arranging your code, using proper indentation, and stuff like that. So, wouldn’t be nice if there would be a tool to solve this issue? Well… there is. There is a Jupyter extension that does exactly that: Code Prettify Jupyter Extension.

Let’s see below how we can install and use it.

Installation

Firstly, we need to install the jupyter_contrib_nbextensions python package. This package will then be used to install the extensions and to activate/deactivate a certain extension.

pip install jupyter_contrib_nbextensions

Then, we need to install the extensions themselves. And what this means is that we basically copy all the javascript and CSS files of all available extensions to the Jupyter data directory and then edit the relevant config files. In Windows, the folder in which these extensions are copied is %APPDATA%\jupyter, in Linux is ~/.local/share/jupyter, and in Mac is ~/Library/Jupyter.

Below is the command that does these things:

jupyter contrib nbextension install --user

After we installed the extensions, we need to enable the code_prettify extension. We do this by using the following command:

jupyter nbextension enable code_prettify/code_prettify

By now, the extension itself is installed.

But what this extension does under the hood is to call the prettifier package specific to the language you’re currently using in the Jupyter notebook. So, for this extension to work, you also need to install a prettifier package appropriate for the kernel you’re using.

For Python, install yapf:

pip install yapf

Or, if you use R, then do:

install.packages(c("formatR", "jsonlite"), repos="http://cran.rstudio.com")

Now you should be ready to use this extension.

How to use it

After you installed the extension, you should see an icon like the one circled in red below:

When you click it, the code in the currently selected cell is prettified.

Example with Python kernel
Example with R kernel

The extension also provides the shortcut CTRL+L for prettifying the current cell (the same thing that the icon does), and CTRL+SHIFT+L for prettifying the whole notebook (if something else is not blocking these shortcuts, of course; but you can configure them).


I hope you found this information useful and thanks for reading!

This article is also posted on Medium here. Feel free to have a look!


Dorian

Passionate about Data Science, AI, Programming & Math

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x