(轉)Python開發規範

轉自:https://www.jianshu.com/p/d414e90dc953javascript

Python風格規範 本項目包含了部分Google風格規範和PEP8規範,僅用做內部培訓學習css

Python風格規範 本項目包含了部分Google風格規範和PEP8規範,僅用做內部培訓學習html


命名規範

Python之父推薦的規範

Type Public Internal
Modules lower_with_under _lower_with_under
Packages lower_with_under  
Classes CapWords _CapWords
Exceptions CapWords  
Functions lower_with_under() _lower_with_under()
Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER
Global/Class Variables lower_with_under lower_with_under
Instance Variables lower_with_under _lower_with_under (protected) or __lower_with_under (private)
Method Names lower_with_under() _lower_with_under() (protected) or __lower_with_under() (private)
Function/Method Parameters lower_with_under  
Local Variables lower_with_under  

應該避免的名稱

1.單字符名稱
2.包/模塊名中使用連字符(-)而不使用下劃線(_)
3.雙下劃線開頭並結尾的名稱(如__init__)

命名約定

1.所謂」內部(Internal)」表示僅模塊內可用, 或者, 在類內是保護或私有的. 2.用單下劃線(_)開頭表示模塊變量或函數是protected的(使用import * from時不會包含). 3.用雙下劃線(__)開頭的實例變量或方法表示類內私有. 4.將相關的類和頂級函數放在同一個模塊裏. 不像Java, 不必限制一個類一個模塊. 5.對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal風格), 可是模塊名應該用小寫加下劃線的方式(如lower_with_under.py). 

註釋規範

文檔字符串

Python使用文檔字符串做爲註釋方式: 文檔字符串是包, 模塊, 類或函數裏的第一個語句. 這些字符串能夠經過對象的doc成員被自動提取, 而且被pydoc所用. 咱們對文檔字符串的慣例是使用三重雙引號」「」( PEP-257 ).java

一個文檔字符串應該這樣組織:
1. 首先是一行以句號, 問號或驚歎號結尾的概述(或者該文檔字符串單純只有一行). 接着是一個空行.
2. 接着是文檔字符串剩下的部分, 它應該與文檔字符串的第一行的第一個引號對齊.python

"""A user-created :class:`Response <Response>` object. Used to xxx a :class: `JsonResponse <JsonResponse>`, which is xxx :param data: response data :param file: response files Usage:: >>> import api >>> rep = api.Response(url="http://www.baidu.com") """ 

行內註釋(PEP8)

行內註釋是與代碼語句同行的註釋
1. 行內註釋和代碼至少要有兩個空格分隔
2. 註釋由#和一個空格開始sql

x = x + 1                 # Compensate for border 

模塊

每一個文件應該包含一個許可樣板. 根據項目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適的樣板.json

# -*- coding: utf-8 -*- # (C) JiaaoCap, Inc. 2017-2018 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) 

函數和方法

一個函數必需要有文檔字符串, 除非它知足如下條件:
1. 外部不可見
2. 很是短小
3. 簡單明瞭api

文檔字符串應該包含函數作什麼, 以及輸入和輸出的詳細描述
文檔字符串應該提供足夠的信息, 當別人編寫代碼調用該函數時, 他不須要看一行代碼, 只要看文檔字符串就能夠了
對於複雜的代碼, 在代碼旁邊加註釋會比使用文檔字符串更有意義.ruby

def simple_func(method, timeout) """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """ 

類應該在其定義下有一個用於描述該類的文檔字符串. 若是你的類有公共屬性(Attributes), 那麼文檔中應該有一個屬性(Attributes)段. 而且應該遵照和函數參數相同的格式.bash

class HTTPAdapter(BaseAdapter): """The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. :param pool_connections: The number of urllib3 connection pools to cache. :param max_retries: The maximum number of retries each connection should attempt. Usage:: >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) """ def __init__(self, pool_connections, max_retries): self.pool_connections = pool_connections self.max_retries = max_retries 

塊註釋和行註釋

對於複雜的操做, 應該在其操做開始前寫上若干行註釋. 對於不是一目瞭然的代碼, 應在其行尾添加註釋.

# We use a weighted dictionary search to find out where i is in # the array. We extrapolate position based on the largest num # in the array and the array size and then do binary search to # get the exact number. if i & (i-1) == 0: # true iff i is a power of 2 

行長度

  1. 每行不超過80個字符
  2. 不要使用反斜槓鏈接行
  3. Python會將 圓括號, 中括號和花括號中的行隱式的鏈接起來 , 你能夠利用這個特色. 若是須要, 你能夠在表達式外圍增長一對額外的圓括號.
NO: query_sql = "SELECT image_id, image_o, image_width, image_height "\ "FROM active_image_tbl "\ "WHERE auction_id=:auction_id AND status=1 " \ "ORDER BY image_id DESC" YES: agent_sql = ("CREATE TABLE IF NOT EXISTS db_agent (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "device_id VARCHAR(128) DEFAULT '', " "status INTEGER DEFAULT 1, " "updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " "created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)") 
在註釋中,若是必要,將長的URL放在一行上。
Yes: 
# See details at # http://www.example.com/us/developer/documentation/api/content/v2.0/fication.html 

換行

  1. 使用4個空格來縮進代碼
  2. 對於行鏈接的狀況, 你應該要麼垂直對齊換行的元素, 或者使用4空格的懸掛式縮進(這時第一行不該該有參數):
# 垂直對齊換行的元素 foo = long_function_name(var_one, var_two, var_three, var_four) # 4空格的懸掛式縮進(這時第一行不該該有參數) foo = long_function_name( var_one, var_two, var_three, var_four) 

空格

  1. 括號內不要有空格
YES: spam(ham[1], {eggs: 2}, []) # 注意標點兩邊的空格 NO: spam( ham[ 1 ], { eggs: 2 }, [ ] ) 
  1. 不要在逗號,分號,冒號前面加空格,而應該在它們的後面加
YES:
if x == 4: print x, y x, y = y, x NO: if x == 4 : print x , y x , y = y , x 
  1. 二元操做符兩邊都要加上一個空格(=, ==,<, >, !=, in, not ...)
  2. 當’=’用於指示關鍵字參數或默認參數值時
def complex(real, imag=0.0): return magic(r=real, i=imag) 
  1. 不要用空格來垂直對齊多行間的標記, 由於這會成爲維護的負擔(適用於:, #, =等)
YES:
foo = 1000  # comment long_name = 2 # comment that should not be aligned NO: foo = 1000 # comment long_name = 2 # comment that should not be aligned 

模塊導入

  1. 每一個導入應該獨佔一行
YES:
import os import sys from subprocess import Popen, PIPE # PEP8 NO: import sys, os 
  1. 模塊導入順序
    1. 標註庫導入
    2. 第三方庫導入
    3. 應用程序指定導入
  2. 每種分組中, 應該根據每一個模塊的完整包路徑按字典序排序, 忽略大小寫.
import foo from foo import bar from foo.bar import baz from foo.bar import Quux from Foob import ar 

TODO註釋

  1. TODO註釋應該在全部開頭處包含」TODO」字符串, 緊跟着是用括號括起來的你的名字, email地址或其它標識符. 而後是一個可選的冒號. 接着必須有一行註釋, 解釋要作什麼
  2. 若是你的TODO是」未來作某事」的形式, 那麼請確保你包含了一個指定的日期(「2009年11月解決」)或者一個特定的事件
# TODO(kl@gmail.com): Use a "*" here for string repetition. # TODO(Zeke) Change this to use relations. 

二元運算符換行(PEP8)

# 不推薦: 操做符離操做數太遠 income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) # 推薦:運算符和操做數很容易進行匹配 income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) 

其它規範

  1. 不要在行尾加分號, 也不要用分號將兩條命令放在同一行.
  2. 除非是用於實現行鏈接, 不然不要在返回語句或條件語句中使用括號. 不過在元組兩邊使用括號是能夠的.
  3. 頂級定義之間空兩行, 方法定義之間空一行

Pandas使用規範

  1. pandas數據結構命名 df_、se_
  2. df取一列,禁止使用df.列名,可使用df['列名'], 建議使用df.loc[:, '列名']
  3. 禁止使用df.ix

目錄結構示例

|--docs |--requests | |--__init__.py | |--_internal_utils.py | |--utils.py | |--api.py |--tests |--setup.py |--README.rst |--LICENSE 

Class結構示例

# -*- coding: utf-8 -*- # (C) JiaaoCap, Inc. 2017-2018 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) """ requests.api This module contains xxx. This module is designed to xxx. """ # stdlib import os import time from base64 import b64encode # 3p try: import psutil exception ImportError: psutil = None import simplejson as json # project from .utils import current_time from ._internal_utils import internal_func class Response(object): """A user-created :class:`Response <Response>` object. Used to xxx a :class: `JsonResponse <JsonResponse>`, which is xxx :param data: response data :param file: response files Usage:: >>> import api >>> rep = api.Response(url="http://www.baidu.com") """ def __init__(self, data, files, json, url) self.data = data @staticmethod def _sort_params(params): """This is a private static method""" return params def to_json(): """The fully method blala bian shen, xxx sent to the server. Usage:: >>> import api >>> rep = api.Response(url="http://www.baidu.com") >>> rep.to_json() """ if self.url == "www": return True return False 

相關連接

相關文章
相關標籤/搜索