Coding Style
Code organization
- #!/usr/bin/python
- docstring
- authorship information
- __author__
- __copyright__
- __credits__
- __license__
- __version__
- __maintainer__
- __email__
- __status__, one of Prototype, Development, or Production
- Import built-in modules, followed by third-party modules, followed by any changes to the path and your own modules
Google Style
Import
- Do not use relative name in import, even if the module is in the same package, use the full package name
Exception
- Use raise myError('Error message'), not raise myError, 'Error message'
- Never use catch-all except, or catch Exception or StandardError
- Use the finally for cleanup, i.e., closing a file
Global variables
Comprehensions & Generator Expressions
- Multiple for clauses or filter expressions are not permitted
Conditional Expressions
- Okay for one-liners, for example, x = 1 if cond else 2
Default Argument Values
- Do not use mutable objects as default values in the function or method definition
Properties
- Use properties in new code to access or set data
True/False evaluations
- A quick "rule of thumb" is that all "empty" values are considered false, so 0, None, [], {}, '' all evaluate false
Python Style Rules
- Semicolons, do not terminate your lines with semi-colons and do not use semi-colons to put two statements on the same line
- Line length, maximum line length is 80 characters
- Indentation, indent your code blocks with 4 spaces, never use tabs or mix tabs and spaces
- Blank Lines, two blank lines between top-level definitions, one blank line between method definitions
- Whitespace, no whitespace inside parentheses, brackets or braces; no whitespace before a comma, semicolon, or colon; no whitespace before the open paren/bracket that starts an argument list, indexing or slicing; surround binary operators with a single space on either side; never use spaces around the '=' sign when passing keyword arguments;
- Shebang Line, most .py files do not need to start with a #! line, start the main file of a program with #!/usr/bin/python
- Comments and Docstrings
- Docstring, should be organized as a summary line (one physical line) terminated by a period, question mark, or exclamation point, followed by a blank line, followed by the rest of the docstring starting at the same cursor position as the first quote of the first line
- Modules, every file should contain license boilerplate, such as Apache 2.0, BSD, LGPL, GPL
- Block and Inline Comments, never describe the code, assume the person reading the code knows Python (though not what you're trying to do) better than you do
- Classes, if a class inherits from no other base classes, explicitly inherit from object
- Files and Sockets, explicitly close files and sockets when done with them
- TODO Comments, use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect
- Imports formatting, imports should be on separate lines
- Python standard library imports
- third-party module or package imports
- third-party module or package imports
- application-specific imports that are part of the same top level sub-package as this file
- Statements, generally only one statement per line
- Access Control, if an accessor function would be trivial you should use public variables instead of accessor functions to avoid the extra cost of function calls in Python
- Naming
- Avoid single character names, dashes (-) in any package/module name
- Use CapWords for class names, but lower_with_under.py for module names, CapWords.py is now discouraged
PEP 8 -- Style Guide for Python Code
Code Lay-out
- Indentation, use 4 spaces per indentation level
- Tabs or Spaces, spaces are the preferred indentation method
- Maximum Line Length, limit all lines to a maximum of 79 characters
- Should a Line Break Before or After a Binary Operator, break before binary operators
- Blank Lines, surround top-level function and class definitions with two blank lines, method definitions inside a class are surrounded by a single blank line
- Imports, imports should usually be on separate lines, imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants
- Absolute imports are recommended
- Wildcard imports (from <module> import *) should be avoided
- Module Level Dunder Names
- docstring
- dunder names, such as __all__, __version__, __author__
- import statements
String Quotes, for triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257
Whitespace in Expressions and Statements
- Avoid extraneous whitespace
- Avoid trailing whitespace anywhere
- Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not)
- If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies)
- If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies)
- Compound statements (multiple statements on the same line) are generally discouraged
Comments
- Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!)
- Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period
- two spaces after a sentence-ending period in multi- sentence comments, except after the final sentence
- Block Comments
- Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment)
- Paragraphs inside a block comment are separated by a line containing a single #
- Inline Comments, inline comments should be separated by at least two spaces from the statement, they should start with a # and a single space
Naming Conventions
- _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore
- single_trailing_underscore_: used by convention to avoid conflicts with Python keyword
- __double_leading_underscore: when naming a class attribute, invokes name mangling
- __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces
- Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names
- Modules should have short, all-lowercase names
- Class names should normally use the CapWords convention
- Exception names should use class convention
- Function and variable names, should be lowercase, with words separated by underscores as necessary to improve readability
- Constants are usually defined on a module level and written in all capital letters with underscores separating words
Reference