Two tools to help you to follow the PEP8 style guide. Here is a more readable version of this guide.

1. flake8

Install

$ pip3 install flake8

Usage

Check all the files in current directory and its sub-directory, but skipping the venv directory.

$ flake8 --exclude=venv .

To avoid run above command with the --exclude option every time, you can add the .flake8 file in current directory with the contents below:

[flake8]
exclude = venv

If you want to enable above configuraiton globally, you can put it in ~/.config/flake8.

Run flake8 --help for complete usage.

2. autopep8

Some of the errors found by flake8 can be fixed automatically by autopep8.

Install

$ pip3 install autopep8

Usage

To modify a file in place (with aggressive level 2):

$ autopep8 --in-place --aggressive --aggressive <filename>
# or
$ autopep8 -i -a -a <filename>

Run autopep8 --help for complete usage.

3. Use them in Vim

It will be great if these two tools can be used directly in Vim, so I use following Vim plugins:

  • vim-flake8
  • vim-autoformat

If you use Vundle to manage Vim plugins like I do, just add followng two lines in your .vimrc file:

Plugin 'nvie/vim-flake8'
Plugin 'Chiel92/vim-autoformat'

And then, run :PluginInstall in Vim to install them.

Also, add following to lines in .vimrc, so that they can be triggered with F3 and F4, respectively.

noremap <F3> :Autoformat<CR>
autocmd FileType python map <buffer> <F4> :call Flake8()<CR>

Reference

  1. flake8
  2. autopep8
  3. vim-flake8
  4. vim-autoformat