DEV Community

Cover image for Python code formatting using Black
Maxime Gaston
Maxime Gaston

Posted on • Edited on

Black Python Python code formatting using Black

What is Black

The official Python style guide is PEP8. Linters such as pycodestyle or flake8 can show you if, according to PEP8, your code is well formatted or not.

The problem is that these tools only report the problems and let the burden to the developers to fix them! Black on the other hand will not only report errors, but also make the necessary changes making you more productive.

To quote the project README:

Black is the uncompromising Python code formatter. By using it, you agree to cede control over minutiae of hand-formatting. In return, Black gives you speed, determinism, and freedom from pycodestyle nagging about formatting. You will save time and mental energy for more important matters.

Install and use Black

Black requires Python 3.6.0+ and is installed using pip:

pip install black
Enter fullscreen mode Exit fullscreen mode

Black is not made to be highly configurable, therefore it is as simple as:

black <file or directory>
Enter fullscreen mode Exit fullscreen mode

This will reformat your code using the Black codestyle which is a subset of PEP8 (except for the default line length: black is 88, PEP8 is 79, use the black -l 79 if it matters to you).

For example if you write the following exaggerated test.py:

def add(
        a,  
        b   
    ):  
    return a+b 

def concatenate(
        s1, 
        s2  
    ):                                                                                                     
    return '{}+{}'.format(
        s1, 
        s2  
    )   

if __name__ == '__main__':
    print(
        add(
            2,  
            3   
            )   
    )   
    print(
        concatenate(
            'two',
            'three'
        )   
    ) 
Enter fullscreen mode Exit fullscreen mode

You can use black test.py to change the test.py to:

def add(a, b):
    return a + b


def concatenate(s1, s2):
    return "{}+{}".format(s1, s2)


if __name__ == "__main__":
    print(add(2, 3))
    print(concatenate("two", "three"))
Enter fullscreen mode Exit fullscreen mode

Editor integration

Black can be used in many editors such as Vim, Emacs, VSCode, Atom...
There are some useful features such as run black on saving.

Have a look at the documentation for a full list of supported editors and how to configure.

Version-Control integration

The black command can also be used as a linter. It can be useful to ensure code quality and consistency in a shared repository with multiple contributors.

To check the code formatting use:

black --check .
Enter fullscreen mode Exit fullscreen mode

You can also show what needs to be done using the --diff option:

black --check --diff .
Enter fullscreen mode Exit fullscreen mode

Now, you'll just need to add this as a step to your CI configuration (just like you would use flake8).

You can also add a pre-commit hook to ensure your commits does not contain unformatted code:

  • install pre-commit:
pip install pre-commit
Enter fullscreen mode Exit fullscreen mode
  • add the .pre-commit-config.yaml to your project:
repos:
- repo: https://github.com/psf/black
  rev: stable
  hooks:
  - id: black
    language_version: python3.6
Enter fullscreen mode Exit fullscreen mode
  • install the hook:
pre-commit install
Enter fullscreen mode Exit fullscreen mode

Now if you try to commit a wrongly formatted files, you will get an error:

git commit -m "test"                        
black....................................................................Failed
hookid: black

Files were modified by this hook. Additional output:

reformatted test.py

1 file reformatted.
Enter fullscreen mode Exit fullscreen mode

Promoting Black

If you like Black, just take a few seconds to star the project on github.

You can also show that you are using the Black codestyle in your project by adding the badge in your README.md:
Code style: black

[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
akaihola profile image
Antti Kaihola

If you're contributing to an Open Source project and want to apply Black to only your contribution without reformatting the complete code base, check out darker โ€“ it's a wrapper for Black for just reformatting the lines you've changed.

Collapse
 
nicolaerario profile image
Nicola Erario

Still with autopep8 here that I like over black for some array formatting behavior. However black really worth a try.

Collapse
 
notsag profile image
Maxime Gaston • Edited

Black also formats list and arrays, trying render a one liner expression if shorter than line-length or else putting one element per line :

# before:

numbers = [1,
     2,
     3
]

# after:

numbers = [1, 2, 3]

It also does the same for function parameters or statements.

Collapse
 
nicolaerario profile image
Nicola Erario

I perfectly know ๐Ÿ˜Ž

Collapse
 
wangonya profile image
Kelvin Wangonya

Very nice! Thanks for the post.

Collapse
 
notsag profile image
Maxime Gaston

My pleasure, I hope you will find Black as useful as I do.

Collapse
 
codemouse92 profile image
Jason C. McDonald

I do love Black!