Python Styleguide

These are general rules for working with python. Much of this was taken from http://www.python.org/dev/peps/pep-0008/. Install and run pep8 to validate your files.

        pip install pep8
        pep8 MY_FILE
    

Coding Style

  • Use soft-tabs with a four space indent.
  • Keep lines fewer than 79 characters.
  • Never leave trailing whitespace.
  • The last line of the file should be a newline.
  • Use spaces around operators, after commas and semicolons.

                    sum = 1 + 2
                    a, b = 1, 2
                    import ipdb; ipdb.set_trace()
                    test = True if 1 > 2 else False
                
  • No spaces after (, [, { or before }, ], ).

                    foo = (1, 2, 3)
                    bar = [1, 2, 3]
                    baz = {'foo': 'bar'}
                
  • Use dictionary literals instead of the dict function.

                    # bad
                    foo = dict(a=1, b=2)
    
                    # good
                    foo = {'a': 1, 'b': 2}
                
  • Continuation lines should be distinguishable from logical lines (ie. different indentation.

                    # bad
                    if (foo == 1 && bar == 2 &&
                        baz == 3):
                        # body omitted
    
                    # good
                    if (foo == 1 && bar == 2 &&
                            baz == 3):
                        # body omitted
                
  • Use two empty lines between classes and module level defs, but only one empty line between class level defs.

                    class some_class(object):
                        # body omitted
    
                        def class_method_1(self):
                            # body omitted
    
                        def class_method_2(self):
                            # body omitted
    
    
                    def some_method():
                        # body omitted
    
    
                    def another_method():
                        # body omitted
                

Documentation

Need to decide on a comment compilation strategy (probably sphinx).

  • Use inline comments sparingly.
  • Inline comments should be separated by at least two spaces from the statement, and start with a # followed by a single space.

Imports

  • Imports should usually be on separate lines.

                    # bad
                    import os, sys
    
                    # good
                    import os
                    import sys
    
                    # except it is ok with import from
                    from subprocess import Popen, PIPE
                
  • Imports should be grouped in the following order:

    1. standard library imports
    2. related third party imports
    3. local application/library specific imports
  • Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports.

Syntax

  • Avoid the inline if/else except in cases where all expressions are extremely trivial. However, do use the inline if/else for single line conditionals.

                # bad
                if some_condition:
                    result = something
                else:
                    result = something_else
    
                # good
                result = something if some_condition else something_else
                
  • Use one expression per branch in an inline if/else. This also means inline if/else must not be nested. Prefer if/else constructs in these cases.

                # bad
                result = something if some_condition else (something2 if some_condition2 else something_else2)
    
                # good
                if some_condition:
                    result = something
                else:
                    result = something2 if some_condition2 else something_else2
                
  • Avoid the inline for/in except in cases where the for/in statement is a one-liner (DO NOT NEST).

                values = [1, 2, 3, 4];
                result = [do_something(v) for v in values]
                
  • Do not use parentheses around the condition of an if/for/while.

                    # bad
                    if (x > 10):
                        # body omitted
    
                    # good
                    if x > 10:
                        # body omitted
                
  • Do not Use spaces around the = operator when assigning default values to method parameters:

                    # bad
                    def my_function(foo = "bar"):
                        # body omitted
    
                    # good
                    def my_function(foo="bar"):
                        # body omitted
                
  • Avoid using Perl-style special variables (like $0-9, $, etc. ). They are quite cryptic and their use in anything but one-liner scripts is discouraged. Prefer long form versions such as $PROGRAM_NAME.

  • Never put a space between a method name and the opening parenthesis.

                    # bad
                    f (3 + 2) + 1
    
                    # good
                    f(3 + 2) + 1
                
  • Use _ for unused, but required variables.

                    def test():
                        return 1, 2
    
                    # bad
                    pointless_var, important_var = test()
    
                    # good
                    _, important_var = test()
                

Naming

  • Use snake_case for modules, methods, and variables.
  • Use CamelCase for classes. (Keep acronyms like HTTP, RFC, XML uppercase.)
  • Use SCREAMING_SNAKE_CASE for other constants.
  • The names of predicate methods (methods that return a boolean value) should begin with question works. (i.e. is, has, etc.).

Exceptions

  • Use exceptions for flow control.

    Add a sample code

  • Never catch Exception or leave the except claus empty.

                    # bad
                    try:
                        # body omitted
                    except:
                        # body omitted
    
                    # or
                    try:
                        # body omitted
                    except Exception:
                        # body omitted
    
                    # good
                    try:
                        # body omitted
                    except ValueError: # or specific exception
                        # body omitted
                

Strings

  • Prefer double-quoted strings. Interpolation and escaped characters will always work without a delimiter change, and ' is a lot more common than " in string literals.

                # bad
                name = 'Bozhidar'
    
                # good
                name = "Bozhidar"
                
  • Avoid concatenating strings, use C-style replacement instead.

                    # bad
                    name = "matt" + " " + "Snider"
    
                    # good
                    name = "matt %s" % "Snider"
                

Regular Expressions

Think about regex rules