Python code formatting using Black
Tags: python, codequality, productivity
Published: 2019-09-09 12:00:45

# What is Black

The official Python style guide is [PEP8](https://www.python.org/dev/peps/pep-0008/). Linters such as [pycodestyle](https://github.com/PyCQA/pycodestyle) or [flake8](http://flake8.pycqa.org/en/latest/) 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](https://github.com/psf/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:

```bash
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](https://black.readthedocs.io/en/stable/the_black_code_style.html) 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`:
```python
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:
```python
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](https://black.readthedocs.io/en/stable/editor_integration.html) 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: 
```yaml
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](https://github.com/psf/black).

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](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
```markdown
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
```