介紹
這篇文檔給出了在主要的Python發行版中标準庫代碼的編碼風格。這篇文檔和PEP 257主要來自于對Guido的Python代碼風格指南論文的改動以及增加了一些Barry的風格指南的内容。
許多項目都有它們自己的編碼風格指南。當發生編碼風格沖突的時候,特定項目的編碼風格指南優先于這裡的風格指南。
Code lay-out
縮進
每個縮進層級使用4個空格。
連續行應當被正确的排列,或者用Python中精确的行垂直的來排列括弧裡面的元素,或者使用懸挂式縮進的來排列。當懸挂式縮進的方式被采用時,下面的情況應當被考慮。在第一行中應該沒有參數,并且後續的縮進應當清楚的将自己标記為一個連續行。
#yes
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
#More indentaion included to distinguish this from the rest.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
對于連續行而言,four-space規則是可選的。
當if表達式的條件部分足夠長,被要求寫到多行中去。可以這樣去做if後面接一個空格,接一個括号,下面的連續行采用四個空格縮進的方式。這樣可以很顯式的去表明if表達式的關系。看看下面的情況。
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment , which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
清單表達式的多行方式也有下面的兩種形式。
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',
)
Tabs or Spaces
空格是Python中推薦的縮進方法。Tab有時候也會用到,但僅僅是為了去對付原有代碼以“Tab”為縮進方式的情況。
Python3不允許混合“Tab”和空格作為縮進方式。
Python2中代碼縮進混合了“Tab”和空格的,“Tab”将會被轉化成空格。當使用-t參數調用python2指令行解析器,解析器将會報出代碼在縮進的過程中非法混合了“Tab”和空格的警告。當使用-tt,這些警告将會變成錯誤。這些參數被極力推薦。
tomorrow will be better , 有空再慢慢補充。
【參考連結】
https://www.python.org/dev/peps/pep-0008/#indentation