Python 的代码风格

有两个供参考

1.PEP 8 http://www.python.org/dev/peps/pep-0008/
            http://www.python.org/dev/peps/pep-0257/

2. Google Python Style Guide http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

代码风格的一致性很重要, 更重要的是在某些情况下为了可读性要灵活变通

缩进用4个空格
不要混用 tab 和空格, python -t / -tt 检查是否混用
限制所有行最长79个字符, 长的块最长72个字符, 换行在二元运算符后面
最上层的函数和类的定义用两个空行分隔
类里的方法用一个空行分隔, python 接受 control-L 作为空格


import 分成几行, from ... import 例外
import 的顺序
Imports should be grouped in the following order:


1. standard library imports
      2. related third party imports
      3. local application/library specific imports
用空行分隔
使用package的绝对路径导入
避免下面这种多余的空格
- Immediately inside parentheses, brackets or braces.


Yes: spam(ham[1], {eggs: 2})
      No:  spam( ham[ 1 ], { eggs: 2 } )

    - Immediately before a comma, semicolon, or colon:

      Yes: if x == 4: print x, y; x, y = y, x
      No:  if x == 4 : print x , y ; x , y = y , x

    - Immediately before the open parenthesis that starts the argument
      list of a function call:

      Yes: spam(1)
      No:  spam (1)

    - Immediately before the open parenthesis that starts an indexing or
      slicing:

      Yes: dict['key'] = list[index]
      No:  dict ['key'] = list [index]

    - More than one space around an assignment (or other) operator to
      align it with another.

      Yes:

          x = 1
          y = 2
          long_variable = 3

      No:

          x             = 1
          y             = 2
          long_variable = 3
算术操作符前后用空格, 二元运算符


Yes:

          i = i + 1
          submitted += 1
          x = x * 2 - 1
          hypot2 = x * x + y * y
          c = (a + b) * (a - b)

      No:

          i=i+1
          submitted +=1
          x = x*2 - 1
          hypot2 = x*x + y*y
          c = (a+b) * (a-b)
当'='用来指明关键字参数或默认参数的时候,两边不要用空格
最好不要把多行语句下在一行里,尤其是if/for/while
错误的注释别没有注释更糟糕.
用英文注释除非120%的确信其它种类的人不会读你的代码
# 后面加个空格
行内注释与表达式之间空至少两格,避免无意义的注释
为所有的公开的modules, functions, classes, methods 写 docstrings


__version__ = "$Revision: 68852 $"
        # $Source$


- Comparisons to singletons like None should always be done with
      'is' or 'is not', never the equality operators.


beware of writing "if x" when you really mean "if x is not None"


Use ''.startswith() and ''.endswith() instead of string slicing to check
      for prefixes or suffixes.


Yes: if foo.startswith('bar'):

        No:  if foo[:3] == 'bar':


For sequences, (strings, lists, tuples), use the fact that empty
      sequences are false.

      Yes: if not seq:
           if seq:

      No: if len(seq)
          if not len(seq)

0 comments: