CSCI 150: Python Style Guide


There are a number of different ways to format python code. Many programmers abuse this freedom and write code that is difficult to read and thus hard to maintain. While there is more than one way to properly format code, here is a set of guidelines which I have found useful in practice. You are not required to abide by them religiously, but I will take marks off for poor formatting. Some of these guidelines may seem amazingly anal, but they really make a difference when reading code.

In the following, each item has a code associated with it to the left of the description of the item. I will use this code to specify the problem when correcting your code. It is up to you to match the code with the item. Hopefully this will encourage you to read this style guide :) As a general rule, the earlier items in a section are more important than the later ones and/or represent more common errors.

In addition, to help catch the simplest style violations I have an automatic style checker program. It won't catch all style errors by any means, but it will catch many of the more common ones. You should run your code through the style checker before you submit it; if it fails, You need to make changes until your code passes, or you convince me that there is a bug in the checker. The python style checker is written (of course) in python ;).

Here is what you have to do to get the style checker working:

Don't be alarmed if there are a lot of errors reported; just go through the file and fix them. Some lines will probably have multiple style violations; you should fix all of them. You'll probably hate this program at first, but your code will become much more readable as a result. If you think you've found a bug in it, let us know at once; this is a work in progress. Note that the style checker may sometimes be too stupid to know when it's in the middle of a comment or a literal string, so it may report errors that aren't really errors in those cases. If so, just disregard them.


The most common style mistakes

These mistakes occur so often that they're almost universal. Therefore, please pay particular attention to avoiding them. Follow the links to get to the descriptions below. Style mistakes followed by an asterisk (*) are caught by the style checker.


Catalog of style mistakes

General

Comments

Documentation Strings

Functions

Exception handling


This style guide was borrowed and modified by Mark Goadrich from a similar version at Caltech, which was modified from the Python Style Guide at http://python.org