Tips For Python

The one about the lazy formatting!

Ignacio Ruiz
3 min readMay 26, 2021

Hey! welcome back, here I will show you a cool Jupyter notebook and Jupyter lab extension that will save you loads of time when you want to make your code look presentable.

Ok, here’s the setup. You are writing some code for a job application or for your job and you will have people look at your code but you want to make sure it looks presentable! Well, there’s an awesome extension for it!

I know it can take a long time and effort to make your code look presentable but not anymore. nb_black is an easy-to-use extension that works like magic! On their website they say:

Black makes code review faster by producing the smallest diffs possible. Blackened code looks the same regardless of the project you’re reading. Formatting becomes transparent after a while and you can focus on the content instead.

I know you want to see how it works so let’s look at how to set it up! First, you want to use

pip install nb_black

It requires Python 3.6.2+ to run but can format Python 2 code too.

After you install it make sure to re-start your Jupyter notebook. Black tends to not load properly if you already have your Jupyter notebook open when you install it. To load Black into your notebook you type

%load_ext nb_black

And that’s it! Now let’s take a look at how it works. nb_black is quite easy to use, once it’s loaded all you need to do is run your cell and nb_black automatically formats the cell to look its best! Here are some examples

In the example above, we can see that the format is completely off. The equal sign is too close to the variable and the list, there are inconsistencies in the quotations and there is too much space or no space at all in between the numbers.

Look at that! now it looks very nice! The spacing is correct and so are the quotation marks! And all it took is to run the cell! Now, let’s look at another more complex example.

This is just an old function I created to calculate a percentage of a column. If we look at it the formatting could use some help. Let me run the cell with Black and see how it turns out!

Look at that, much better! We can see more consistent quotations, spacing of the variables, and in between lines of code.

There you go! a simple way to make your code more presentable for your next project!

--

--