1. Code Layout
Use 4 spaces per indentation level.Do not use tab, only use space for indentation.
Limit all lines to a maximum of 79 characters.
Separate top-level function and class definitions with two blank lines, otherwise, use one blank line between class method or block code within function.
Try not to "from a import *", "import one-class" in each line
2. Comment
Principle: "Comments that contradict the code are worse than no comments."My colleague suggest to use documentation string: """ comments """ for each functions/classes defined, this may help automatically generate documentation.
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code.
Use inline comments sparingly.
3. Naming Convention
Modules should have short, all-lowercase names. (May have underscores if improves readability) --- ex. calculate_integral.py
Class names should normally use the CapWords convention. --- ex. class KeyDataStructure (object):
Function names should be lowercase (May have underscores if improves readability) --- ex. def calc_two_integral():
Method follows the same naming convention as function. While for non-public methods and instance variables, add "_" before the name
Constant defined under module level, use all capital with underscores. --- ex. MAX_ITER
4. Programming Recommendations
Code should be written in a way that does not disadvantage other implementations of Python. --- ex. do not use a += b for string operation, use ''.join()
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name.
Use string methods instead of the string module.
Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.
Object type comparisons should always use isinstance() instead of comparing types directly.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Don't compare boolean values to True or False using ==.
There is really no need to rigidly memorize all of these. Just keep them in mind, and the code would be much better.