-
Notifications
You must be signed in to change notification settings - Fork 21
Python Code Standards
Use 2 spaces for each indent level. Class names should start with a Capital letter. Other variables should be camelBack case. Private variables start with two underscores: __ Protected variables should start with one underscore: _ Function definitions should have at least one line of whitespace afterwards. except:
with no exception should only be used in extraordinary circumstances; instead something like except KeyError:
or except Exception as e: print(repr(e))
would be better so only the provided exception is ignored or something is done with the exception.
For python 2 code, it should have:
from __future__ import division, print_function, unicode_literals, absolute_import
import warnings
warnings.simplefilter('default',DeprecationWarning)
before any code to simplify porting to python 3. (Importing unicode_literals can be skipped if it causes problems and this is discussed with other developers.)
Functions should have a docstring, which is right after the line defining the function and are between triple quotes """. The triple quotes should be on their own line, and an additional level of indentation should be provided for the documentation comments. Each input should be listed in the fashion below, starting with @In
, then the name of the input, the type of the input, (optional) and a brief description. For output variables, the line starts with @Out
, the name of the output variable, followed by the type of the output, and a brief description of it.
In the event the return object is not a named variable [and it is not possible to do so (e.g. the method is very short and an addition of a named variable does not represent an added value for the readability of the code)], the name of the method should be listed instead.
Other comments not at the start of a function, method or class should use the # character to start them.
def sqr(x):
"""
Returns the square of the argument.
@ In, x, float, number to be squared
@ Out, result,float, square of x
"""
result = x*x #square by multiplying
return result
def sqrWithOptionalArg(x=2.0):
"""
Returns the square of the argument.
@ In, x, float, optional, number to be squared
@ Out, result,float, square of x
"""
result = x*x #square by multiplying
return result
def printWolf():
"""
Print the message 'Wolf'
@ In, None
@ Out, None
"""
print("Wolf")
def returnSize(x):
"""
Return the size of an array
@ In, x, numpy.array, the array whose size needs to be determined
@ Out, returnSize, int, the size of the array 'x'
"""
return x.size
The so-called "wild importing" approach is FORBIDDEN, i.e. :
from aModule import *