Write better Python

In order to write better Python code, you can check out the PEP8 guidelines.

Specifically:

Use lines of 79 characters or less. To set a marker that will help you keep that line length in VIm, add this to your .vimrc:

:set colorcolumn=79

When breaking a long expression into several lines, add 4 spaces of indent to each continuation line. Example:

long_string = "The quick brown fox jumps over the lazy dog" \
    + "and feels as if he were in the seventh heaven of typography"

In such cases, instead of the backslash character (\) to continue the expression, prefer surrounding the expression with parentheses, preserving the added indentation that makes it easier to read. For example:

long_string = (
    "The quick brown fox jumps over the lazy dog" +
    "and feels as if he were in the seventh heaven of typography"
)

When defining class methods, differentiate public functions from low-level ones by naming them accordingly. Examples:

  • Public methods should be in format lowercase_underscore,
  • Protected methods: _leading_underscore,
  • Private methods: __double_leading_underscore.

When comparing items you can, and should, use inline negation as in if a is not b, rather than negate positive expressions like if not a is b. This adds to the clarity of your code.

Instead of checking for cases when a container is empty using if len(my_list) == 0, use if not my_list. Whenever your list is empty this expression will evaluate to False as well.

To easier keep your code style aligned with the good practices, use PyLint in your console. If you use VIm as your editor, install Syntastic which enforces the rules known from PyLint.

Read more on these guidelines in Effective Python, and compare with PEP 8.