A summary of python code style conventions

“PEP 8: Style Guide for Python Code” and “PEP 257: Docstring Conventions” aren’t exactly long, but they’re also not easily skimmable.

As I’ve just started to learn python, I should make an effort to internalise these best-practice conventions. To help me do that, I’m going to summarise PEP 8 and 257 here, as a quick reference for myself and anyone else who might find it useful.

This is not quite an exhaustive summary: I have omitted the really obvious stuff, and in some cases I’ve picked one approach where PEP8 allows a few.

These standards can hopefully help in every coders’ ongoing mission to write readable and expressive code.

Indentation, line-length & code wrapping

# Good:
result = some_function_that_takes_arguments(
    'argument one,
    'argument two',
    'argument three'
)

# Bad:
result = some_function_that_takes_arguments(
'argument one,
'argument two', 'argument three')
result2 = some_function_that_takes_arguments('argument one', 'argument two', 'argument three')

Imports

# Good:
import os
import sys
from mypkg.sibling import example
from subprocess import Popen, PIPE # Acceptable
from .sibling import example # Acceptable

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

Whitespace and newlines

# Good:
spam(ham[1], {eggs: 2})
if x == 4:
    print x, y
    x, y = y, x
dict['key'] = list[index]
y = 2
long_variable = 3
hypot2 = x*x + y*y
c = (a+b) * (a-b)
def complex(real, imag=0.0):
    return magic(r=real, i=imag)
do_one()
do_two()

# Bad
spam ( ham[ 1 ], { eggs: 2 } ) # spaces inside brackets
if x == 4 : print x , y ; x , y = y , x # inline statements, space before commas
dict ['key'] = list [index] # space before dictionary key
y             = 2 # Using spaces to line up assignment operators
long_variable = 3
hypot2 = x * x + y * y # Too much space around operators
c = (a + b) * (a - b) # Too much space around operators
def complex(real, imag = 0.0):
    return magic(r = real, i = imag) # Spaces in default values

Comments

def my_function():
    """ A one-line docstring """

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

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

    """

Naming conventions

class MyClass:
    """ A purely illustrative class """

    __property = None

    def __init__(self, property_value):
        self.__property = property_value

    def get_property(self):
        """ A simple getter for "property" """

        return self.__property

    @classmethod
    def default(cls):
        instance = MyClass("default value")
        return instance
By @nottrobin