Coding Style Guidelines and Conventions
Our main coding bible is the Style Guide for Python Code which can be found here.
Import Statements
It's vitally important to know where symbols/functions are defined, so never, ever do this:
from somemodule import "*"
For example, if you do:
from numarray import "*"
you will be polluting your global namespace with close to 300 names!
For numarray functions the recommended form of import is:
import numarray as na
import numarray.random_array as ra
import numarray.linear_algebra as la
import numarray.mlab as mlab
A few explicit imports such this is probably okay:
from numarray import array, zeros, innerproduct, matrixmultiply
Naming Conventions
Module names should have short, lowercase names and without underscores.
Class names should be specified using mixed case. The first letter in the name must be C.
Method and function names should use mix capitalization. Each word must have the first letter in uppercase.:
def CalculateGradient(x, y):
pass
Data attribute or Variable names should start with small letter. Use mix case letter for subsequent words. In python data attributes override method attributes, which may cause hard to find bugs in large problems. Therefore strictly follow this convention.
Indentation
- Use 4 spaces per indentation level. Do not use tabs.
If you use Emacs remember to set:
(setq-default indent-tabs-mode nil) (setq-default tab-width 4) - Limit all lines to a maximum of 79 characters
- Separate top-level function and class definitions with two blank lines
- Separate method definitions inside a class with single blank line
White Spaces
Avoid white spaces in the following situations:
- Immediately inside parentheses, brackets or braces:
Yes: spam(ham[1], {eggs: 2}) No: spam( ham[ 1 ], { eggs: 2 } ) - Immediately before a comma, semicolon, or colon:
Yes: if x == 4: print x, y; x, y = y, x No: if x == 4 : print x , y ; x , y = y , x - Immediately before the open parenthesis that starts the argument list of a function call:
Yes: spam(1) No: spam (1) - Immediately before the open parenthesis that starts an indexing or slicing:
Yes: dict[’key’] = list[index] No: dict [’key’] = list [index] - More than one space around an assignment (or other) operator to align it with another:
Yes: x = 1 y = 2 long_variable = 3 No: x = 1 y = 2 long_variable = 3 - Use spaces around arithmetic operators:
Yes: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) No: i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) - Don't use spaces around the
=sign when used to indicate a keyword argument or a default parameter value:Yes: def Complex(real, imag=0.0): return magic(r=real, i=imag) No: def Complex(real, imag = 0.0): return magic(r = real, i = imag)
Last modified 2007-03-29 12:07 AM