formatting with python black
Spent part of the day comparing Python linters including autopep8 — complies with PEP 8 (one of the oldest formatting tools), yapf — by Google (stands for ‘yet another python formatter’!), and Black- by a core Python developer.
Seems like yapf has been popular for quite a while but Black is gaining popularity. Black is known as the uncompromising code formatter
and it will reformat code consistently whereas yapf can return different formatting if you rerun code through the formatter multiple times. Black will also format for the latest Python 3.6 features. Yapf seems very flexible with formatting rules, while black is not as configurable although it is possible (for example, line length). Black will format quotes with double quotes, while the other two will leave as single quotes. Another difference noticed, is that Black and yapf will move closing brackets to a next line while autopep8 will leave on the same line.
I tried out Black and got it working — to check my code prior to making git commits by using pre-commit hooks and Flake8 validation with the following steps:
>> pip install pre-commit
Add `.pre-commit-config.yaml` file
repos:- repo: https://github.com/ambv/black rev: stable hooks: - id: black language_version: python3.6- repo: https://github.com/pre-commit/pre-commit-hooks rev: v1.2.3 hooks: - id: flake8
Install pre-commit in your local git directory with above settings
>> pre-commit install
Add `.flake8` file. This will validate that the formatting done complies with PEP8.
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9
Add .python-version file, for example:
3.6.0
Make specified Python version available for local environment:
>> pyenv local 3.6.0
When you’re ready to make a commit, follow normal git commands:
>> git add <file name>
>> git commit -m “<message>”
At this point, pre-commit git hooks are run.
You may see something like this if formatting is needed:
To accept these formatting changes, run the same git commands:
>>git add <file name>
>>git commit -m “<message>”
This time around you should see that your formatted code is now passing Black linter and Flake8 validation:
Next step will be to incorporate into the CI/CD pipeline!