Flake8 is a Python library that wraps PyFlakes, pycodestyle and Ned Batchelder’s McCabe script. It is a great toolkit for checking your code base against coding style (PEP8), programming errors (like “library imported but unused” and “Undefined name”) and to check cyclomatic complexity.
If you are not familiar with the term cyclomatic complexity, it is a software metric created by Thomas J. McCabe to measure the number of independent paths through the source code. Generally speaking, the higher number of ifs inside a function, the higher number of paths it will have, thus a higher cyclomatic complexity. Of course there are other control flow operations that impact the calculus of the cyclomatic complexity. It is also referred as McCabe complexity.
Speaking about coding style, I also like to follow the Django Coding Style on the Django projects I develop. This style standard is only enforced when writing code for inclusion in Django.
Easiest way to get started is installing it using pip:
Inside the Django project dir, run the command:
Or you can pass the path to a file/dir:
The output will be something like that:
The output is formatted as:
file path :
line number :
column number :
error code :
Error code prefix:
- E***/W***: pep8 errors and warnings
- F***: PyFlakes codes (see below)
- C9**: McCabe complexity plugin mccabe
- N8**: Naming Conventions plugin pep8-naming
You can see the full list of error codes in the links below:
You can pass some project-based configuration parameters using a
setup.cfg file. If you already have one, just edit
it. If that is not the case, create a file named
setup.cfg in the project root.
Those are the basic configurations I use in every project. The exclude parameter is used to ignore file/dirs. The default line-length is 79. I find it too small and sometimes makes the code look worse. So, following the Django code style guidelines, I stick with 119.
See the full list of options.
In-Line Ignoring Errors
# noqa in the end of the line.
Or you can pass the specific error code you want to ignore:
Running flake8 on Travis CI
The example below is a .travis.yml file from a project of mine. You can run flake8 checks very easily just by adding the commands inside the script list.
That’s it! As you can see, it is really easy to start making your Django project PEP8 complaint with flake8.