Automatically Review Code for Python Projects Using flake8

Image for post

Regardless of which programming language you’re using, each has a unique development style when multiple people are using it.

I’ll now introduce flake8, a tool for checking Python syntax. SideCI supports code review automation for Python projects using flake8.

Install flake8

You can install flake8 using pip commands.

$ pip install flake8

How to Use flake8

Basically, all you have to do is designate a file or directory path following the flake8 command.

$ flake8 url.py
url.py:22:1: H306  imports not in alphabetical order (urlparse, urllib)
url.py:30:3: E111 indentation is not a multiple of four
url.py:31:1: W293 blank line contains whitespace
url.py:58:1: E302 expected 2 blank lines, found 1
  :

Add the  option and the statistics will appear at the end. These begin from things with lots of errors, so they’ll be in order of support.

39      E111 indentation is not a multiple of four
1       E128 continuation line under-indented for visual indent
1       E302 expected 2 blank lines, found 1
10      F821 undefined name 'cmp'
1       H306  imports not in alphabetical order (urlparse, urllib)
3       W291 trailing whitespace
4       W293 blank line contains whitespace
1       W391 blank line at end of file

By adding the  option, it’ll be easier to figure out what parts of the source code need to be revised.

$ flake8  --show-source url.py 
url.py:22:1: H306  imports not in alphabetical order (urlparse, urllib)
import urllib
^
url.py:63:73: W291 trailing whitespace
    provides a better interface for comparing and manipulating URLs than
                                                                        ^
url.py:108:20: F821 undefined name 'cmp'
            return cmp(self.to_string(), str(other))
                   ^

About Options

flake8 options are as follows. You can designate error codes to ignore using  or display PEP 8 messages related to errors using . PEP 8 is a Python coding style guide.

Automatic Translation

autopep8 allows you to automatically resolve problems with indents and blank spaces. You can install it using pip.

$ pip install autopep8

Afterwards, all you have to do is replace them with autopep8.

$ autopep8 -i url.py

SideCI allows you to automate code review in Python projects using flake8. This service is useful for automatically reviewing pushes to GitHub or developing in groups on cloud services. You can use setup.cfg or tox.ini to change your preferences on SideCI.

Be sure to give it try.

flake8 3.3.0 : Python Package Index

More articles about Python(pep8, pyflakes, flake8, haking, Pylint)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.