PEP 8

PLWM follows PEP 8 -- Style Guide for Python Code as a guideline for code formatting. There are a couple of important parts to this:

  • All indentation should use spaces, with 4 spaces per level of indentation; never mix tabs and spaces. (in fact, don't use tabs at all)
  • Limit all lines to a maximum of 79 characters.
  • Don't align code after the start of a line; for example, this is wrong:
    foo    = 0
    blargh = 1
    
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -=, etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), booleans (and, or, not), arithmetic (+, -, /, *, **), and string formatting (%).
  • Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value.
  • Separate top-level function and class definitions with two blank lines.
  • Separate method definitions inside a class with a single blank line.
  • Use ASCII encoding unless a comment or docstring needs to mention an author name that requires Latin-1; otherwise, use \x, \u or \U escapes to include non-ASCII data in a string literal.
  • Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the "def" line.
  • Always use 'self' for the first argument to instance methods.
  • Always use 'cls' for the first argument to class methods.

There's plenty more recommendations in PEP 8, and it is definitely worth reading in full for any Python developer.

Luckily, most modern editors can be configured to automatically work within these rules.

Vim

Several settings can have a bearing on coding within PEP 8:

  • set tabstop=4 - Set tabs to 4 characters wide.
  • set softtabstop=4 - When using backspace to delete indentation at the start of a line, delete 4 spaces at once. (this makes space-indented code act a bit more like tab-indented code)
  • set shiftwidth=4 - When using >> or << to indent or outdent a block of code, indent or outdent by 4 characters.
  • set expandtab - Always expand tabs to spaces; don't leave raw tab characters in the code.

To automatically set these all when working on Python code, put the following code in your ~/.vimrc:

autocmd FileType python set tabstop=4|set softtabstop=4|set shiftwidth=4|set expandtab

To convert a tab-indented (or, worse, mixed tab and space indentation) file to your current tab settings, use the following command:

:retab