Programming is as much an art as a science. The undisputed “bible” of programming,
a 2,500 page multivolume work by Donald Knuth, is called The Art of Computer Pro
gramming. Many books have been written on Literate Programming, recognizing that
humans, not just computers, must read and understand programs. Here we pick up on
some issues of programming style that have important ramifications for the readability
of your code, including code layout, procedural versus declarative style, and the use of
loop variables.
Python Coding Style
When writing programs you make many subtle choices about names, spacing, com
ments, and so on. When you look at code written by other people, needless differences
in style make it harder to interpret the code. Therefore, the designers of the Python
language have published a style guide for Python code, available at http://www.python
.org/dev/peps/pep-0008/. The underlying value presented in the style guide is consis
tency, for the purpose of maximizing the readability of code. We briefly review some
of its key recommendations here, and refer readers to the full guide for detailed dis
cussion with examples.
Code layout should use four spaces per indentation level. You should make sure that
when you write Python code in a file, you avoid tabs for indentation, since these can
be misinterpreted by different text editors and the indentation can be messed up. Lines
should be less than 80 characters long; if necessary, you can break a line inside paren
theses, brackets, or braces, because Python is able to detect that the line continues over
to the next line, as in the following examples:
cv_word_pairs = [(cv, w) for w in rotokas_words
… for cv in re.findall(‘[ptksvr][aeiou]’, w)] cfd = nltk.ConditionalFreqDist(
… (genre, word)
… for genre in brown.categories()
… for word in brown.words(categories=genre))ha_words = [‘aaahhhh’, ‘ah’, ‘ahah’, ‘ahahah’, ‘ahh’, ‘ahhahahaha’,
… ‘ahhh’, ‘ahhhh’, ‘ahhhhhh’, ‘ahhhhhhhhhhhhhh’, ‘ha’,
… ‘haaa’, ‘hah’, ‘haha’, ‘hahaaa’, ‘hahah’, ‘hahaha’]
If you need to break a line outside parentheses, brackets, or braces, you can often add
extra parentheses, and you can always add a backslash at the end of the line that is
broken:
if (len(syllables) > 4 and len(syllables[2]) == 3 and
… syllables[2][2] in [aeiou] and syllables[2][3] == syllables[1][3]):
… process(syllables)if len(syllables) > 4 and len(syllables[2]) == 3 and
… syllables[2][2] in [aeiou] and syllables[2][3] == syllables[1][3]:
… process(syllables)
Typing spaces instead of tabs soon becomes a chore. Many program
ming editors have built-in support for Python, and can automatically
indent code and highlight any syntax errors (including indentation er
rors). For a list of Python-aware editors, please see http://wiki.python
.org/moin/PythonEditors.
