Python track: coding 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 we have found useful in practice. You are not required to abide by them religiously, but we 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. We 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 we 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 will be required to run your code through the style checker before you submit it; if it fails, it won't be graded (unless you can convince us that the style checker itself has a bug, which is entirely possible). The python style checker is written (of course) in python ;-).

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

Now you're all set. You will be able to use the style checker from any directory you're in, and you'll never have to download it again. To style check a file called e.g. foo.c, do:

    % python_style_check

You can also style check multiple files all at once:

    % python_style_check

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



Documentation Strings


Exception handling