Python Coding Standards » History » Revision 4
Revision 3 (Neil Voss, 03/19/2010 02:19 PM) → Revision 4/7 (Neil Voss, 03/19/2010 02:22 PM)
h1. Python Coding Standards
This document is a list of python coding standards. To add a new standard copy the template below and modify it.
see also http://emg.nysbc.org/wiki/index.php/Appionscripts_formatting_rules
----
h2. +Name of Coding Standard+
h3. Definition
What is the coding standard
h3. Justification
Why is the coding standard important
h3. Example
GOOD:<pre>
this is a good example code
</pre>
BAD:<pre>
this is a bad example code
</pre>
----
h1. Python Coding Standards for AMI
----
h2. +Use tabs instead of spaces+
h3. Definition
Use tabs instead of spaces for inline code
h3. Justification
It is important to be consistent. People like different sizes of columns, some like 8 spaces, others 4, 3, or 2. With tabs each individual can customize their viewer.
h3. Example
GOOD:<pre>
if True:
<tab>while True:
<tab><tab>print "tab"
<tab>break
</pre>
BAD:<pre>
if True:
while True:
print "tab"
break
</pre>
----
h2. +Checking beginning or ending of strings+
h3. Definition
Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.
h3. Justification
startswith() and endswith() are cleaner and less error prone.
h3. Example
GOOD:<pre>
if foo.startswith('bar'):
</pre>
BAD:<pre>
if foo[:3] == 'bar':
</pre>
----
h2. +Never use @from module import *@+
h3. Definition
Never use @from module import *@, use @import module@ instead
h3. Justification
It is hard to track where functions come from when @import *@ is used
h3. Example
GOOD:<pre>
import numpy
a = numpy.ones((3,3))
</pre>
BAD:<pre>
from numpy import *
a = ones((3,3))
</pre>
----
h2. +Appion image data naming conventions+
h3. Definition
# never use 'image' or 'img'
# use 'imgdict' for image dictionaries
# use 'imgarray' for image numarrays
# use 'imgname' for image filenames
# use 'imgtree' for the main list of image dictionaries
# use 'imglist' for a list of image data
h3. Justification
If you are consistent with your names people can read your code.
h3. Example
GOOD:<pre>
for imgdict in imgtree:
imgarray = imgdict['image']
imgname = imgdict['filename']
</pre>
BAD:<pre>
for image in imgs:
array = image['image']
name = image['filename']
</pre>
----
h2. +Use descriptive variables+
h3. Definition
Use descriptive variables, @asdf@ is not a variable.
h3. Justification
No one understands shorthand variables.
h3. Example
GOOD:<pre>
imgarray = mrc.read('leginon_image.mrc')
particle1 = imgarray[47, 21]
particle1 = imgarray[10, 15]
class = [particle1, particle1]
</pre>
BAD:<pre>
i = mrc.read('x.mrc')
prtl1 = i[47, 21]
prtl2 = i[10, 15]
cls = [prtl1, prtl2]
</pre>