[effective python]改善python代码的91个建议-chapter1

## 建议1 使用pep8校验代码规范性
pep8 --first test.py
长字符串换
print 'You\'d need to know \'bout escapes with' \
      '\\ that do \n newlines and \t tabs.'


print ('You\'d need to know \'bout escapes with' 
      '\\ that do \n newlines and \t tabs.') :?: 

 
print语句下面应该有个空行(new line)

pep8 --show-source --show-pep8 test.py


推荐使用空格来进行缩进。

Tab应该只在现有代码已经使用tab进行缩进的情况下使用,以便和现有代码保持一致。

Python 3不允许tab和空格混合使用。

Python 2的代码若有tab和空格混合使用的情况,应该把tab全部转换为只有空格。

当使用命令行运行Python 2时,使用-t选项,会出现非法混用tab和空格的警告。当使用-tt选项时,这些警告会变成错误。强烈推荐使用这些选项!

每行最大长度(Maximum Line Length)
将所有行都限制在79个字符长度以内。

有时续行只能使用反斜杠才。例如,较长的多个with语句不能采用隐式续行,只能接受反斜杠表示换行:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

   
空行(Blank Line)
使用2个空行来分隔最高级的函数(function)和类(class)定义。

使用1个空行来分隔类中的方法(method)定义。

Imports
Imports应该分行写,而不是都写在一行,例如:
# 分开写
import os
import sys
# 不要像下面一样写在一行
import sys, os
这样写也是可以的:

from subprocess import Popen, PIPE
Imports应该写在代码文件的开头,位于模块(module)注释和文档字符串之后,模块全局变量(globals)和常量(constants)声明之前。


Imports应该按照下面的顺序分组来写:

标准库imports
相关第三方imports
本地应用/库的特定imports
不同组的imports之前用空格隔开。

Python有一种独一无二的的注释方式: 使用文档字符串.
文档字符串是包, 模块, 类或函数里的第一个语句.
这些字符串可以通过对象的__doc__成员被自动提取, 并且被pydoc所用.
(你可以在你的模块上运行pydoc试一把, 看看它长什么样).
我们对文档字符串的惯例是使用三重双引号”“”( PEP-257 ).
一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行).
接着是一个空行. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐.
下面有更多文档字符串的格式化规范.
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """
    pass

   
代码规范:
http://nanshu.wang/post/2015-07-04/
https://www.douban.com/note/134971609/
https://lizhe2004.gitbooks.io/code-style-guideline-cn/content/python/python-pep8.html
http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/#comments

将notepad++ python语言默认的tab改成4个空格的方法:
设置->首选项->制表符设置->python->取消‘使用默认值’

其它代码规范标准和工具:
Google python style guide
Pylint,Pyflakes,Pychecker 等

三元操作符
x=0
y=-2
print x if x<y else y
输出-2

python不支持switch case
可以用if..elif..else 代替
或者用
def f(x):
    return {
        0:"first",
        1:"second",
        2:"third",
        3:"four"
    }.get(x, "error input")

   

定义常量,参考:http://www.malike.net.cn/blog/2013/11/03/python-constants/
class _const:
    class ConstError(TypeError): 
        pass
    class ConstCaseError(ConstError): 
        pass
    
    def __setattr__(self, name, value):
        if (self.__dict__.has_key(name)):
            raise self.ConstError, "Can't change const.%s" % name
        if not name.isupper():
            raise self.ConstCaseError, \
                  'const name "%s" is not all uppercase' % name
        self.__dict__[name] = value 
        
    def __delattr__(self, name):
        self.__dict__.has_key(name):
            raise self.ConstError, "Can't unbind const const instance attribute (%s)" % name

        raise AttributeError, "const instance has no attribute '%s'" % name
        

import sys
sys.modules[__name__] = _const()


使用const
import const
const.COMPANY = "NMG"



   

猜你喜欢

转载自lhdst-163-com.iteye.com/blog/2327552