Skip to content

Latest commit

 

History

History
45 lines (36 loc) · 3.37 KB

File metadata and controls

45 lines (36 loc) · 3.37 KB

Code formatter

A code formatter takes care of formatting your code so that it adheres to the styling standards. For Python, a popular code formatter is black. Black is PEP 8 compliant but also adds some own flavor to the code. Comparing code that has been formatted with black makes it easier to spot the differences. You can even try it out online.

You first need to install black using

pip install black

You can then use black running it as

black Material_Part3_Formatter/example1.py

Please note that the formatter reformats the file in-place, that means, substituting the content of the original file!

Now you can check with flake8 if the file is compliant with PEP 8:

flake8 Material_Part3_Formatter/example1.py

You will notice that flake8 is not returning errors except a line length error for one of the comment lines: Note that black does not reformat comments other than inserting proper whitespace before and after the #.

Task 1: Reformat example1.py and example2.py using black. Compare to your own reformatted files.

Black configuration

Sometimes you only want to check what black would actually reformat. In order to do so, run

black Material_Part3_Formatter/example1.py --diff

or

black Material_Part3_Formatter/example1.py --diff --color

Task 2: Try this out with your own reformatted files from Part 1 of this course (PEP styleguide).

Black with jupyter notebooks

To use black with jupyter notebooks, you need to install the extension using

pip install black[jupyter]

Task 3: Try out the notebook extension with this example.

Black with VSCode

If you are using an IDE, specifically Visual Studio Code, you can set up black as the default formatter for your *.py files. Follow the instructions provided here.

For more tips and tricks, see this page.