2011年8月21日 星期日

PEP 8 -- Style Guide for Python Code (1)

Code layout
1. Indentation
  a. Use 4 spaces per indentation level.
  b. Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent.
  # Aligned with opening delimiter
  foo = long_function_name(var_one, var_two,

                           var_three, var_four)
  # hanging indent
  # there should be no arguments on the first line and
  # further indentation should be used to clearly distinguish
  # itself as a continuation line

  def long_function_name(
          var_one, var_two, var_three,
          var_four):
      print(var_one)


2. Tabs or Spaces?
  a. Never mix tabs and spaces.
  b. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.

3. Maximum Line Length
  a. Limit all lines to a maximum of 79 characters.
  b. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.
  c. The preferred place to break around a binary operator is after the operator, not before it.

4. Blank lines
  a. Separate top-level function and class definitions with two blank lines.
  b. Method definitions inside a class are separated by a single blank line.

5. Encodings
  a. Code in the core Python distribution should always use the ASCII or Latin-1 encoding (a.k.a. ISO-8859-1). For Python 3.0 and beyond, UTF-8 is preferred over Latin-1, see PEP 3120.
  b. Latin-1 (or UTF-8) should only be used when a comment or docstring needs to mention an author name that requires Latin-1; otherwise, using \x, \u or \U escapes is the preferred way to include non-ASCII data in string literals.


Imports
1. Imports should usually be on separate lines.
  Yes: import os
       import sys
       from subprocess import Popen, PIPE
  No:  import sys, os


2. Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

3. Imports should be grouped in the following order:
  (1) standard library imports
  (2) related third party imports
  (3) local application/library specific imports

4. You should put a blank line between each group of imports.

5. Put any relevant __all__ specification after the imports.

6. Always use the absolute package path for all imports.

沒有留言:

張貼留言