Python

A Summary of PEP 8: Style Guide for Python Code and PEP 257: Docstring Conventions.

Most programming languages follow a basic style or formatting standard to make it easy for others to read your code. In Python, we have the PEP 8 and the PEP 257 conventions. PEP stands for “Python Enhancement Proposal”.

“PEP 8: Style Guide for Python Code” and “PEP 257: Docstring Conventions” are documents that contain conventions meant to standardise Python code.The PEPs are not laws that are forced upon you. Violating the style guides will not make your code not run but you will get dirty looks from whoever has to read or maintain your code.

The following post is my attempt at summarising the Style Guides. This is not an exhaustive summary: I selected most of the important points.

Code lay-out

  • Always use four spaces to indent code. Do not use tabs, tabs introduce confusion and are best left out.
  • Wrap your code so that lines don’t exceed 79 characters. This helps users with small displays and makes it possible to have several code files open side by side on larger displays.
  • When vertical aligning text, there should be no arguments on the first line
# Good:
my_list = [
    1, 2, 3
    4, 5, 6,
]

foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

# Bad:
foo = long_function_name(var_one, var_two,
    var_three, var_four)

result = some_function_that_takes_arguments(
'argument one',
'argument two', 'argument three')

Whitespace.

  • Use 2 blank lines around top level functions and classes.
  • Use 1 blank line to separate large blocks of code inside functions.
  • 1 blank line before class method definitions.
  • Avoid extraneous whitespace.
  • Use blank lines sparingly.
  • Always surround binary operators with a space on either side but group them sensibly.
  • Don’t use spaces in keyword arguments or default parameter values.
  • Don’t use whitespace to line up operators.
  • Multiple statements on the same line are discouraged.
  • Avoid trailing whitespace anywhere
# Good:
x = 1
y = 2
long_variable = 3

if x == 4: print x, y
x, y = y, x
spam(ham[1], {eggs: 2})

i = i + 1
c = (a+b) * (a-b)
hypot2 = x*x + y*y

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()



# Bad:
x             = 1
y             = 2
long_variable = 3

if x == 4 : print x , y
x , y = y , x
spam( ham[ 1 ], { eggs: 2 } )

i=i+1
c = (a + b) * (a - b)
hypot2 = x * x + y * y

if foo == 'blah': do_blah_thing()
do_one; do_two(); do_three()

Comments

  • Comments should be complete sentences in most cases.
  • Keep comments up to date
  • Write in “Strunk & White “English
  • Inline comments should be separated by at least two spaces from the statement and must start with ‘#’ and a single space.
  • Block comments should be indented to the same level as the code that follows them.
  • Each line in block comments starts with ‘#’.
  • Write docstrings for all public modules, functions, classes and methods.
  • Docstrings start and end with """ e.g """ A Docstring. """.
  • Single line docstrings can all be on the same line.
  • Docstrings should describe the method or function’s effect as a command.
  • Docstrings should end in a period.
  • When documenting a class, insert a blank line after the docstring.
  • The last """ should be on a line by itself
def kos_root():
    """Return the pathname of KOS root directory."""
    global _kos_root
    blah
    blah

def a_complex_function(parameter=False):
    """
    A multiline docstring.

    Keyword arguments:
    parameter -- an example parameter (default False)

    """

Imports

  • Don’t use wildcards.
  • Try to use absolute imports over relative ones
  • Don’t import multiple packages per line
  • When using relative imports, be explicit with (.)
# Good:
import os
import sys
from subprocess import Popen, PIPE

import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

from . import sibling
from .sibling import example

# Bad:
import os, sys # multiple packages
import sibling # local module without "."
from mypkg import * # wildcards

Naming Conventions

  • Use CapWords/CamelCase convention for class names.
  • Use short, lowercase identifiers separated by underscores for modules and functions.
  • Always use “self” for the first argument to instance variables.
  • Always use “cls” for the first argument to class methods.
  • Constants should be in ALL_CAPS_WITH_UNDERSCORES.

Programming Conventions

  • Comparisons to singletons like None should be done with ‘is’ or ‘is not’, never the equality operators.
  • Always use a ‘def’ statement instead of an assignment statement that binds a lambda expression directly to an identifier.
  • Either all return statements in a function return an expression or none of them should.
# Good:

if foo is not None:
def f(x): return 2*x

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0: return None return math.sqrt(x) # Bad: if foo != None: f = lambda x: 2*x def foo(x): if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s