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
If you installed the packages via the requirements.txt
file from your assignment repo, then you already have it installed.
You can then use black running it as
black chapter2_3/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 chapter2_3/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 #.
Subtask (iii): Reformat example1.py
and example2.py
using black. Compare to your own reformatted files from the previous assignemt.
Black configuration
Sometimes you only want to check what black would actually reformat. In order to do so, run
black chapter2_3//example1.py --diff
or
black chapter2_3/example1.py --diff --color
Task 3: Now you should have completed all edits on your assignment repo and should be able to submit the results (if the autograding and CI do not raise any issues).
Black with jupyter notebooks
The new versions of black directly allow you to run it on jupyter notebooks,
Subtask (iv): Try out reformatting notebooks with example_jupyter.ipynb
.
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.