python代碼格式規範

來源:互聯網
上載者:User

標籤:順序   tps   ash   顯示   cstring   max   zmq   index   overflow   

目前的規範基於pep-0008

基本格式縮排

使用4個空格進行縮排

行寬

每行代碼盡量不超過80個字元

理由:

  • 這在查看side-by-side的diff時很有協助
  • 方便在控制台下查看代碼
  • 太長可能是設計有缺陷
換行

Python支援括弧內的換行。這時有兩種情況。

  1. 第二行縮排到括弧的起始處
foo = long_function_name(var_one, var_two,                         var_three, var_four)
  1. 第二行縮排4個空格,適用於起始括弧就換行的情形
def long_function_name(        var_one, var_two, var_three,        var_four): print(var_one)

使用反斜線\換行,二元運算子+ .等應出現在行首,並與上一行的.或=對齊;或者縮排4個空格。長字串也可以用此法換行

foo = variable_with_long_name     + another_variable     + variablesession.query(MyTable)        .filter_by(id=1) .one()this_is_a_very_long(function_call, ‘with many parameters‘) .that_returns_an_object_with_an_attributeprint ‘Hello, ‘ ‘%s %s!‘ % (‘Harry‘, ‘Potter‘)

多個元素的list或者tuple,在起始括弧後換行,第二行縮排4個空格

items = [    ‘this is the first‘, ‘set of items‘, ‘with more items‘, ‘to come in this line‘, ‘like this‘]

禁止複合陳述式,即一行中包含多個語句:

# yesdo_first()do_second()do_third()# nodo_first();do_second();do_third();

if/for/while一定要換行:

# yesif foo == ‘blah‘: do_blah_thing()# noif foo == ‘blah‘: do_blash_thing()
空行
  • 模組層級函數和類定義之間空兩行;
  • 類成員函數之間空一行;
  • 不要使用太多的連續空行來區分代碼的邏輯塊
class A:    """This is a simple docstring."""    def __init__(self): pass def hello(self): passdef hello(name): print "Hello %s!" % namedef main(): pass
  • 可以使用多個空行分隔多組相關的函數
  • 函數中可以使用空行分隔出邏輯相關的代碼
運算式空格
  • 一元運算子不加空格
  • 在二元運算子兩邊各空一格[=,-,+=,==,>,in,is not, and]:
# yesexp = -1.05i = i + 1submitted += 1x = x * 2 - 1hypot2 = x * x + y * yc = (a + b) * (a - b)# noexp = - 1.05i=i+1submitted +=1x = x*2 - 1hypot2 = x*x + y*yc = (a+b) * (a-b)
  • 函數的參數列表中,,之後要有空格
# yesdef complex(real, imag): pass# nodef complex(real,imag): pass
  • 函數的參數列表中,預設值等號兩邊不要添加空格
# yesdef complex(real, imag=0.0): pass# no def complex(real, imag = 0.0): pass
  • 左括弧之後,右括弧之前不要加多餘的空格
# yesspam(ham[1], {eggs: 2})value = my_list[index]# nospam( ham[1], { eggs : 2 } )value = my_list[ index ]
  • 字典、列表對象的左括弧之前不要多餘的空格
# yesdict[‘key‘] = list[index]# nodict [‘key‘] = list [index]
  • 不要為對齊指派陳述式而使用的額外空格
# yesx = 1y = 2long_variable = 3# nox = 1y = 2long_variable = 3
比較
  • 使用變數在左,常量在右
  • 不顯示進行對True、False的比較
  • 否定比較採用,foo not in bar的形式,而不是not foo in bar
  • 使用instance(a, C)進行執行個體的類型檢查,而不是type(A) is C
# yesif method == ‘md5‘: passif not foo: passif foo not in bar: passif instance(a, C): pass# noif ‘md5‘ == method: passif foo == False: passif not foo in bar: passif type(A) is C: pass
引號

簡單說,自然語言使用雙引號,機器標示使用單引號,因此 代碼裡 多數應該使用 單引號

  • 自然語言 使用雙引號 "..."
    例如錯誤資訊;很多情況還是unicode,使用u"你好世界"
  • 機器標識 使用單引號 ‘...‘ 例如dict裡的key
  • Regex 使用原生的雙引號 r"..."
  • 文檔字元 使用三個雙引號 """......"""
import語句
  • import語句應該分行書寫
# yesimport osimport sys# noimport sys,os# yesfrom subprocess import Popen, PIPE
  • import語句應該使用 absolute import
# yesfrom foo.bar import Bar# nofrom ..bar import Bar
  • import語句應該放在檔案頭部,置於模組說明及docstring之後,於全域變數之前;
  • import語句應該按照順序排列,每組之間用空行分隔
import osimport sysimport msgpackimport zmqimport foo
  • 匯入其他模組的類定義時,可以使用相對匯入
from myclass import MyClass
  • 如果發生命名衝突,則可使用命名空間
import bar import foo.barbar.Bar()foo.bar.Bar()
註解區塊注釋

#號後空一格,段落間用空行分開(同樣需要#號)

# 塊注釋# 塊注釋## 塊注釋# 塊注釋
行注釋

至少使用兩個空格和語句分開,使用有意義的注釋

# yesx = x + 1  # 邊框加粗一個像素# nox = x + 1 # x加1 
docstring

docstring的規範在 PEP 257 中有詳細描述,其中最其本的兩點:

  1. 所有的公用模組、函數、類、方法,都應該寫docstring。私人方法不一定需要,但應該在def後提供一個塊注釋來說明。
  2. docstring的結束"""應該獨佔一行,除非此docstring只有一行。
"""Return a foobarOptional plotz says to frobnicate the bizbaz first.""""""Oneline docstring"""
命名規範
  • 應避免使用小寫字母l(L),大寫字母O(o)或I(i)單獨作為一個變數的名稱,以區分數字1和0
  • 包和模組使用全小寫命名,盡量不要使用底線
  • 類名使用CamelCase命名風格,內部類可用一個底線開頭;
    約定的縮寫保留原樣,例如使用HTTPWriter而不是HttpWriter
  • 函數使用底線分隔的小寫命名,lowercase_with_underscores
  • 當參數名稱和Python保留字衝突,可在最後添加一個底線,盡量不是使用縮寫或自造的詞
  • 常量使用以底線分隔的大寫命名,UPPERCASE_WITH_UNDERSCORES
  • Precompiled regular expressions: name_re
MAX_OVERFLOW = 100Class FooBar:        def foo_bar(self, print_): print(print_) 

Function and method arguments:

  • Class methods: cls as first parameter.
  • Instance methods: self as first parameter.
  • Lambdas for properties may have the first parameter replaced with x, as in display_name = property(lambda x: x.real_name or x.username).
編碼
  • 檔案使用UTF-8編碼
  • 檔案頭部加入#-*-coding:utf-8-*-標識

python代碼格式規範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.