Coding Guidelines and PEP-8

Why do we care about consistent code formatting:

  • You read more code than you write (?), ergo "readability counts"
  • Whith multiple contributors one coding style makes a difference and avoids annoyance and pollutation of the git/hg/svn change logs
  • Python coding style reference: PEP-8
  • Coding guidelines extend to the documentations and how to format consistent doc strings (see documenting with Sphinx)

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

But most importantly: know when to be inconsistent – sometimes the style guide just doesn’t apply. When in doubt, use your best judgement. Look at other examples and decide what looks best. And don’t hesitate to ask!

Two good reasons to break a particular rule:

1) When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules. 2) To be consistent with surrounding code that also breaks it (maybe for historic reasons) – although this is also an opportunity to clean up someone else’s mess (in true XP style).

Indentation

  • Never mix tabs and spaces
  • Always use 4 spaces
# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

Maximum Line Length

  • Limit all lines to a maximum of 79 characters.

Imports

import os import sys

  • Do not import everything like this: from numpy import * (prevend name clashes)

  • In case this causes a name clash

    from myclass import MyClass
    from foo.bar.yourclass import YourClass

    do this:

      import myclass
      import foo.bar.yourclass

Naming conventions

  • To prevent name clashes, append an underscore _ (do not abbriviate or otherwise)
  • class names: CapWords
  • Exceptions: CapWords, with Error suffix (if it is an error)
  • Function names: lowercase, with words separated by underscores as necessary to improve readability

More

  • Blank lines
  • Character encoding: UTF-8
  • How to import modules
  • Whitespace in Expressions and Statements
  • Code comments
  • Docstrings (see Sphinx)
  • Naming conventions

In [ ]: