loading...
Cover image for Python code formatting using Black

Python code formatting using Black

notsag profile image Maxime Gaston Updated on ・3 min read

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

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

black <file or directory>

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'
        )   
    ) 

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"))

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 .

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

black --check --diff .

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
  • 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
  • install the hook:
pre-commit install

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.

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)

Posted on by:

notsag profile

Maxime Gaston

@notsag

SRE, opensource enthusiast and sport addict.

Discussion

markdown guide
 

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.

 

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

 

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.

 
 
 

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