Python Code Style Guidelines

Guidlines for well designed and written Python Code
  • Use good modular design. Think carefully about the functions and data structures that you are creating before you start writing code.
    • The main function should not contain low-level details. It should be a high-level overview of your solution (remember top-down design).
    • As a general guide, no function should be longer than a page long. Of course there are exceptions, but these should truly be the exception.

  • Use good error detection and handling. Always check return values from functions, and handle errors appropriately.
      x = positive_compute(y, z) 
      if ( x <= 0 ): 
        print ("positive_compute error...setting x to 1")
        x = 1
      # continue on knowing x will be > 0, set by return value or error handling code 

  • Use descriptive names for variables, functions, classes. You don't want to make function and variable names too long, but they should be descriptive (e.g. use "getRadius" or "get_radius" rather than "foo" for a function that returns the value of the radius of a circle). Also, stick with Python-style naming conventions (e.g. i and j for loop counter variables).

  • Pick a capitalization style for function names, local variable names, global variable names, and stick with it. For example, for function name style you could do something like "square_the_biggest" or "squareTheBiggest" or "SquareTheBiggest". By convention, variable names start with a lower case character.

  • Line Length: your source code should not contain lines that are longer than 80 characters long. If you have a line that is longer than 80 character, break it up into multiple lines. Use the '\' character at the end of a line to tell the Python interpreter that the statment continues on the next line:

    Here is an example of how to break up a long boolean expression into three lines:

      if ( ((blah < 0 ) and (grr > 234)) \ 
           or ((foo == 3456) and (grr <= 4444)) \
           or ((blah > 10) and (grr == 3333))  \
        print ("this crazy condition is true")    	
        print ("and my code is really easy to read because")
        print ("I didn't wrap lines!")
        print ("this crazy condition is false")    	
    The easiest way to make sure you are not adding lines longer than 80 characters wide is to always work inside a window that is exactly 80 characters wide. If your line starts wrapping around to the next line, its too long. Below are more examples of handling long lines of different types.

  • Comment your code!

    File Comments: Every .py file should have a high-level comment at the top describing the file's contents, and should include your name(s) and the date.

    This program approximates PI using the Monte Carlo Simulation method.
    It randomly generates positions for "darts" thrown at cicle inside a 
    unit square, and count the number landing inside the circle to estimate PI.
    (a nice visualization:
    (newhall, 2016)

    Function Comments: Every function should have a comment describing:

    1. what function does;
    2. what its parameter values are
    3. what value(s) it returns (if a function returns one type of value usually, and another value to indicate an error, your comment should describe both of these types of return values).
    If a function has some tricky code, then use in-line comments to explain what it is doing.

    My advice on writing function comments: write the function's comment first, then write the function code. For complicated functions, having a comment that lists the steps of the algorithm, will help you

    When commenting stick to a particular style. For example:

    def approx_pi(n):
      Function:  approx_pi 
      computes an approximation of pi using:
         pi/6 = 1/2 + (1/2 x 3/4) 1/5 (1/2)^3  + (1/2 x 3/4 x 5/6) 1/7 (1/2)^5 +
        n: number of terms in the series to sum
       returns: the approximate value of pi obtained by suming the first n terms
                in the above series
                returns zero on error (if n is non-positive)
       # note: approx_pi is likely complicated enough to have in-line comments
       #       describing parts of the code
    def square_the_biggest(n1, n2):
      Function: square_the_biggest
        Returns the square of the largest of its two input values
        n1: one real value 
        n2: the other real value
        returns: the square of the larger of n1 and n2 
    In-line Comments: Any complicated, tricky, or ugly code sequences in the function body should contain in-line comments describing what it does (here is where using good function and variable names can save you from having to add comments).

    Inline comments are important around complicated parts of your code, but it is important to not go nuts here; over-commenting your code can be as bad as under-commenting it. Avoid commenting the obvious. Your choice of good function and variable names should make much of your code readable. For example, a comment like the following is unnecessary as it adds no information that is not already obvious from the python code itself, and it can obscure the truley important comments in your code:

      # this is a bad in-line comment:
      x = x + 1   # increment the value of x 

    Class Comments: Every Class should have a high-level comment describing what it does, and each of its method functions should have a comments similar to those of regular functions.

    Some more Line Length Examples:
    Some more examples of how to break up long lines of different types into multiple lines in your code.

    Here is an example of breaking up a long comment into multiple lines:

      x = foo(x);  # compute the value of the next prime number
                   # that is larger than x  (foo is a really bad 
                   # choice for this function's name) 
    Here are two ways to break up a long string that you want printed on a single output line:
      # (1) use two calls to print, and add a , after the first: 
      print ("here is a really long string with an int value, %d,") %(x),
      print (" that I want to print to stdout")
      # (2) use one call to print  and the stmt continuation char '\' 
      #     between the two strings spanning two lines:
      print ("here is a really long string with an int value, %d," \
             " that I want to print to stdout") %(x)