Style

Why Style

What do we mean when we say coding style? Think of style as an error of form, not function. Although “Wrecking Ball” was a fine song (function), the performance that accompanied it… not so fine (form). It’s the difference between using a double negative (grammatically incorrect) versus ending a sentence with a preposition (bad form).

Python, like all coding languages, has its own style conventions, and it’s important that you follow them. Style is critical to make sure your code is readable, that it is polished and presentable, and most importantly, it conveys that you are a competent coder.

In Wall Street they judge you by the quality of your suit; in Silicon Valley, they judge you by the quality of your code. And a critical aspect of that is how nicely it is presented.

PEP 8

The standard documentation that defines all Python style guides is called PEP 8; there are other PEPs, like PEP 100 which determine how to handle Unicode strings, and PEP 20 which is the “Zen of Python”. While these are all interesting, and you should read them if you are truly passionate about Python, PEP 8 is the one that concerns us here.

There are several things from PEP8 that I want to emphasize.

1. Soft Tabs

Soft tabs is a way to convert the tab character to spaces; in Python, spaces are preferred to tab. So soft tabs enables you to quickly add 4 spaces. Here is a guide to do this in Eclipse.

2. Line Length

Remember those really bad websites that have long lines of text that make you scroll sideways to read them? We hate that. We really, really hate that. It’s a computer science pet peeve.

In honor of our hatred, we have a restriction to 100 character limit for all lines of code. Single line commments, however, can only go up to 80 characters. Docstrings, which we will discuss further on in this section, and can only go up to 72 characters.

3. Import Statements

Import statements should be alphabetically arranged and on separate lines.

No:

import os, sys, cs1lib

Yes:

import cs1lib
import os
import sys

In Python, however, there are 2 ways to import. One is the above import x fashion. The other is from x import y. The first style should always precede the second. Here is an example.

import os
import sys


from cs1lib import *

Notice the two lines of indentation between the two types of import.

4. Naming

Functions and methods should be

lowercase_separated_by_underscores

Constants should be in

ALL_CAPS_WORDS_SEPARATED_BY_UNDERSCORES

Classes (which you will learn about later in the term)

CamelCaseLikeSo

Documentation

Documentation covers all the other aspects of style, from comments to larger descriptions of what each function does and the file does. Block comments and docstrings both begin with a triple quotation mark (single or double is accepted). For more details on documentation, visit PEP 257 which covers all docstring conventions.

Docstrings can either be multi-line

'''
Example multi-line docstring in Python.
Many lines. Very documentation.
'''

or single-line.

'''Single line docstring in Python.'''

Every file should begin with a docstring explaining the purpose of the file and other meta-data like the author name, date it was written. Let’s create a sample docstring for the CS1 library.

'''
Defines graphics functions used for CS 1.
Provides wrapper functions around more complex PyQt functions.
Author:  Weifu Wang
Date:    August 2012
Version: 1.0
'''

That would go at the very top of the cs1Library.py file.

Docstrings for functions serve a different purpose. With a single glance, they explain everything that function does. Here are the critical components of a function docstring:

Let’s take an example of whether we should go to CS1 class. In the beginning, we start with a simple model that always tells us to always attend class.

def goToClass():
    '''Outputs whether to go to CS1.'''
    print "Of course!"

But this ignores the realities of life! Weather (ugh, Winter), how far you have to walk (Life Sciences! Life is too hard…), whether you can afford to skip class, and whether it was a pong night yesterday (#hangover – don’t lie, you know this to be true). So let’s make a more complex model.

def goToClass(weather, location, pong, grade):
    '''
    Outputs whether to attend CS1 class based on many factors.

    Keyword arguments:
    weather -- A float in Farenheit for the temperature outside
    location -- A string with the name of the building in which
                CS1 class will be held
    pong -- A boolean value of whether it's a pong night
    grade -- A float for the grade currently held in the class
    '''
    pass

But this is silly! Why would we print to the screen when we could return a boolean. Let’s add this fix.

def goToClass(weather, location, pong, grade):
    '''
    Outputs whether to attend CS1 class based on many factors.

    Keyword arguments:
    weather -- A float in Farenheit for the temperature outside
    location -- A string with the name of the building in which
                CS1 class will be held
    pong -- A boolean value of whether it's a pong night
    grade -- A float for the grade currently held in the class

    Keyword returns:
    A boolean whether you should go to CS1 class.
    '''
    pass

And there is a complete docstring example. Besides, this, you should use inline comments to describe any particularly complicated lines of code. What counts as a complicated line of code? This is something that you’ll learn over time. For now, think of it this way: if there’s a line of code that is not obvious, it deserves a comment.

Automatic Style Checker

To make your life easier, there is an automatic style checker that makes sure your code follows all the conventions of PEP8.

The site allows direct file uploads, and it will return to you the direct feedback for all the errors. Like golf, a better file receives less feedback, with a perfect file receiving no feedback. Check out the site at python-style.com.

Things not covered by the automatic style checker that you still should watch out for.

Resources

Want a much easier to read guide?

Read David Gooder’s amazing style guide.