Python编码规范

2018-06-26  本文已影响0人  猫猫头1984

Python编码规范

2018.6


1. 缩进

foo = long_function_name(var_one, var_two,
                         var_three, var_four)
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]

result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )
my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)
# 没有额外的缩进,但条件判断的语句会和后面的语句产生视觉冲突
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# 增加一个注释,在能提供语法高亮的编辑器中可以有一些区分
if (this_is_one_thing and
    that_is_another_thing):
    # 这里添加注释,区分前后两部分的语句
    do_something()

# 在条件判断的语句添加额外的缩进,和后面语句区分
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

 


2. 换行

query_str = ("select DriveLetter " 
             "from Win32_Volume " 
             "where Label = \"%s\"") % (args.logusn)
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())
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)
if foo == 'something': do_blah_thing()
do_one(); do_two(); do_three()

 


3. 空行

class Common(object):
    """common class,提供通用的方法"""
    def __init__(self):
        """common的构造器:"""
        pass

    def method1(self):
        pass

    def method2(self):
        pass


def method3():
    pass

 


4. Imports导入

# 正确
import os
import sys

# 错误
import os, sys
from subprocess import Popen, PIPE
"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'John'

import os
import sys
package
├── __init__.py
├── sub_pkg1
│   ├── __init__.py
│   ├── module_x.py
│   ├── module_y.py
└── sub_pkg2
    ├── __init__.py
    └── module_z.py

# module_x.py
import module_y  # 隐式相对导入
from module_y import var  # 隐式相对导入
from . import module_y  # 显式相对导入
from .module_y import var  # 显式相对导入
from sub_pkg1 import module_y  # 绝对导入

 


5. 表达式和语句中的空格

# 正确写法
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

# 错误写法
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# 正确写法
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

# 错误写法
def complex(real,imag = 0.0):
    return magic(r = real, i = imag)

 


6. 注释

# 块注释段落1
#
# 块注释段落2
#
# 块注释段落3

下面是一个py文件开头块注释的格式。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# title           :backup_full.py
# description     :MySQL全量备份
# author          :张雪峰
# date            :20180601
# version         :1.0
# notes           :
# python_version  :3.6
#==============================================================================
x = x + 1                 # 行内注释

 


7. 命名

package
├── __init__.py
├── sub_pkg1
│   ├── __init__.py
│   ├── module_x.py
│   ├── module_y.py
└── sub_pkg2
    ├── __init__.py
    └── module_z.py
class BackupFile(object):
    """Backup_File class"""
class SomeCustomError(Exception):
    def __init__(self,str_length):
        super(SomeCustomError,self).__init__()
        self.str_length = str_length
        
try:
    s = raw_input("输入一行字符串:\n")
    # 输入字符串长度超过指定长度范围,引发异常
    if (length < len(s)):
        raise SomeCustomError(length)
except SomeCustomError as x:
    print("捕获自定义异常")
__all__ = ['var1', 'var2', 'var3']
_name = 'var4'
status_code = 0

def thread_fun(self, cmdstr):
    """单个线程"""
class Kls(object):
    no_inst = 0
    def __init__(self):
        Kls.no_inst = Kls.no_inst + 1

    @classmethod
    def get_no_of_instance(cls):
        return cls.no_inst
HOST = "192.168.1.10"
PORT = 7777
NUM_LOG = 100000

 


8. 异常

class SomeCustomError(Exception):
    def __init__(self,str_length):
        super(SomeCustomError,self).__init__()
        self.str_length = str_length
try:
    process_data()
except Exception as exc:
    raise DataProcessingFailedError(str(exc))
# 正确写法
try:
    import platform_specific_module
except ImportError:
    platform_specific_module = None
    
# 错误写法 
try:
    import platform_specific_module
except:
    platform_specific_module = None
# 正确写法
try:
    value = collection[key]
except KeyError:
    return key_not_found(key)
else:
    return handle_value(value)

# 错误写法 
try:
    return handle_value(collection[key])
except KeyError:
    # 可能会捕获handle_value()引发的KeyError,而不是collection的 
    return key_not_found(key)

 


9. 接收和返回

 


10. 其他

with open("/document/foo.txt") as f:
    data = f.read()
    
try:   
    f = open("/document/foo.txt", "r")   
except IOError as e:
    print(e)
finally:
    f.close()
# 正确写法
def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

# 错误写法
def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)
# 推荐写法       
if foo.startswith('bar'):
    pass

# 不推荐写法
if foo[:3] == 'bar':
    pass
# 推荐写法  
if isinstance(obj, int):
    pass

# 不推荐写法  
if type(obj) is type(1):
    pass
# 推荐写法   
if greeting:
    pass

# 不推荐写法
if greeting == True:
    pass

# 不推荐写法
if greeting is True:
    pass
上一篇 下一篇

猜你喜欢

热点阅读