Intro to Black – The Uncompromising Python Code Formatter

There are several Python code checkers available. For example, a lot of developers enjoy using Pylint or Flake8 to check their code for errors. These tools use static code analysis to check your code for bugs or naming issues. Flake8 will also check your code to see if you are adhering to PEP8, Python’s style guide.

However there is a new tool that you can use called Black. Black is a Python code formatter. It will reformat your entire file in place according to the Black code style, which is pretty close to PEP8.


Installation

Installing Black is easy. You can just use pip for that:

pip install black

You can also configure popular text editors and IDEs to use Black following these instructions.

Now that Black is installed, let’s give it a try!


Using Black

Black requires you to have some code to run it against. Let’s create a simple function that has lots of parameters and then run Black on that script.

Here’s an example:

def long_func(x, param_one=None, param_two=[], param_three={}, param_four=None, param_five="", param_six=123456):
    print("This function has several params")

Now in your terminal, try running black against your code file like this:

black long_func.py

When you run this command, you should see the following output:

reformatted long_func.py
All done!
1 file reformatted.

This means that your file has been reformatted to follow the Black standard.

Let’s open the file up and see what it looks like:

def long_func(
    x,
    param_one=None,
    param_two=[],
    param_three={},
    param_four=None,
    param_five="",
    param_six=123456,
):
    print("This function has several params")

As you can see, Black has put each of the parameters on their own line.


Checking Files for Formatting

If you don’t want Black to change your file, but you want to know if Black thinks a file should be changed, you can use one of the following command flags:

  • --check– which checks if the file should be reformatted, but doesn’t actually modify the file
  • --diff– which writes out a diff of what Black would do to the file, but doesn’t modify the file

I like to use these to do a test run on my files and see how Black will reformat my code. I haven’t been using Black a long time, so this lets me see if I like what Black is going to do without actually doing anything.


Wrapping Up

I like Black. I think it could be really useful, especially in an organization when it comes to enforcing a certain Python style. Note that Black defaults to 88 characters for its line length, but you can change that using -l

or --line-length

if you need to. There are also a few other options you might find useful listed on the project’s page. If you get a chance, I think you should give Black a try!


Related Reading