點擊上方“ 開發(fā)者技術(shù)前線 ”,選擇“星標”
13:21 在看?真愛
來源:KotlinPython, 作者:PythonGao
我是PythonGao。?一名微軟工程師。今天給大家分享一下Google Python 編程規(guī)范。適合入門者學(xué)習(xí)。
分號
不要在行尾加分號, 也不要用分號將兩條命令放在同一行.
行長度
每行不超過80個字符
例外:
-
長的導(dǎo)入模塊語句
-
注釋里的URL
不要使用反斜杠連接行.
Python會將?圓括號, 中括號和花括號中的行隱式的連接起來?, 你可以利用這個特點. 如果需要, 你可以在表達式外圍增加一對額外的圓括號
Yes:?foo_bar(self,?width,?height,?color=
'black'
,?design=
None
,?x=
'foo'
,
?????????????emphasis=
None
,?highlight=
0
)
?????
if
?(width?==?
0
?
and
?height?==?
0
?
and
?????????color?==?
'red'
?
and
?emphasis?==?
'strong'
):
如果一個文本字符串在一行放不下, 可以使用圓括號來實現(xiàn)隱式行連接:
x?=?(
'This?will?build?a?very?long?long?'
?????
'long?long?long?long?long?long?string')
在注釋中,如果必要,將長的URL放在一行上。
Yes:??#?See?details?at??????#?http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.htmlNo:??#?See?details?at?????#?http://www.example.com/us/developer/documentation/api/content/\?????#?v2.0/csv_file_name_extension_full_specification.html
??????
#?http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
No:??
#?See?details?at
?????
#?http://www.example.com/us/developer/documentation/api/content/\
?????
#?v2.0/csv_file_name_extension_full_specification.html
注意上面例子中的元素縮進; 你可以在本文的?縮進?部分找到解釋.
括號
寧缺毋濫的使用括號
除非是用于實現(xiàn)行連接, 否則不要在返回語句或條件語句中使用括號. 不過在元組兩邊使用括號是可以的
Yes:?
if
?foo:
?????????bar()
?????
while
?x:
?????????x?=?bar()
?????
if
?x?
and
?y:
?????????bar()
?????
if
?
not
?x:
?????????bar()
?????
return
?foo
?????
for
?(x,?y)?
in
?dict.items():?...
No:??
if
?(x):
?????????bar()
?????
if
?
not
(x):
?????????bar()
?????
return
?(foo)
縮進
用4個空格來縮進代碼
絕對不要用tab, 也不要tab和空格混用. 對于行連接的情況, 你應(yīng)該要么垂直對齊換行的元素(見?行長度?部分的示例), 或者使用4空格的懸掛式縮進(這時第一行不應(yīng)該有參數(shù)):
Yes:???#?Aligned?with?opening?delimiter???????foo?=?long_function_name(var_one,?var_two,????????????????????????????????var_three,?var_four)???????#?Aligned?with?opening?delimiter?in?a?dictionary???????foo?=?{???????????long_dictionary_key:?value1?+????????????????????????????????value2,???????????...???????}???????#?4-space?hanging?indent;?nothing?on?first?line???????foo?=?long_function_name(???????????var_one,?var_two,?var_three,???????????var_four)???????#?4-space?hanging?indent?in?a?dictionary???????foo?=?{???????????long_dictionary_key:???????????????long_dictionary_value,???????????...???????}No:????#?Stuff?on?first?line?forbidden??????foo?=?long_function_name(var_one,?var_two,??????????var_three,?var_four)??????#?2-space?hanging?indent?forbidden??????foo?=?long_function_name(????????var_one,?var_two,?var_three,????????var_four)??????#?No?hanging?indent?in?a?dictionary??????foo?=?{??????????long_dictionary_key:??????????????long_dictionary_value,??????????????...??????}
???????foo?=?long_function_name(var_one,?var_two,
????????????????????????????????var_three,?var_four)
???????
#?Aligned?with?opening?delimiter?in?a?dictionary
???????foo?=?{
???????????long_dictionary_key:?value1?+
????????????????????????????????value2,
???????????
...
???????}
???????
#?4-space?hanging?indent;?nothing?on?first?line
???????foo?=?long_function_name(
???????????var_one,?var_two,?var_three,
???????????var_four)
???????
#?4-space?hanging?indent?in?a?dictionary
???????foo?=?{
???????????long_dictionary_key:
???????????????long_dictionary_value,
???????????
...
???????}
No:????
#?Stuff?on?first?line?forbidden
??????foo?=?long_function_name(var_one,?var_two,
??????????var_three,?var_four)
??????
#?2-space?hanging?indent?forbidden
??????foo?=?long_function_name(
????????var_one,?var_two,?var_three,
????????var_four)
??????
#?No?hanging?indent?in?a?dictionary
??????foo?=?{
??????????long_dictionary_key:
??????????????long_dictionary_value,
??????????????
...
??????}
空行
頂級定義之間空兩行, 方法定義之間空一行
頂級定義之間空兩行, 比如函數(shù)或者類定義. 方法定義, 類定義與第一個方法之間, 都應(yīng)該空一行. 函數(shù)或方法中, 某些地方要是你覺得合適, 就空一行.
空格
按照標準的排版規(guī)范來使用標點兩邊的空格
括號內(nèi)不要有空格.
Yes:?spam(ham[1],?{eggs:?2},?[])No:??spam(?ham[?1?],?{?eggs:?2?},?[?]?)
spam
(
ham
[1]
,?{
eggs
:?
2
},?
[]
)
No
:??
spam
(?
ham
[?1?]
,?{?
eggs
:?
2
?},?
[?]
?)
不要在逗號, 分號, 冒號前面加空格, 但應(yīng)該在它們后面加(除了在行尾).
Yes:?if?x?==?4:?????????print?x,?y?????x,?y?=?y,?xNo:??if?x?==?4?:?????????print?x?,?y?????x?,?y?=?y?,?x
?????????
print
?x,?y
?????x,?y?=?y,?x
No:??
if
?x?==?4?:
?????????
print
?x?,?y
?????x?,?y?=?y?,?x
參數(shù)列表, 索引或切片的左括號前不應(yīng)加空格.
Yes:?spam(1)no:?spam?(1)Yes:?dict['key']?=?list[index]No:??dict?['key']?=?list?[index]
no
:?spam?(
1
)
Yes:?dict[
'key'
]?=?list[
index
]
No:??dict?[
'key'
]?=?list?[
index
]
在二元操作符兩邊都加上一個空格, 比如賦值(=), 比較(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布爾(and, or, not). 至于算術(shù)操作符兩邊的空格該如何使用, 需要你自己好好判斷. 不過兩側(cè)務(wù)必要保持一致.
Yes:?x?==?1No:??x<1
No:??x<1
當(dāng)’=’用于指示關(guān)鍵字參數(shù)或默認參數(shù)值時, 不要在其兩側(cè)使用空格.
Yes:?def?complex(real,?imag=0.0):?return?magic(r=real,?i=imag)No:??def?complex(real,?imag?=?0.0):?return?magic(r?=?real,?i?=?imag)
real
,?
imag
=
0.0
):?
return
?magic(r=
real
,?i=
imag
)
No:??def?
complex
(
real
,?
imag
?=?
0.0
):?
return
?magic(r?=?
real
,?i?=?
imag
)
不要用空格來垂直對齊多行間的標記, 因為這會成為維護的負擔(dān)(適用于:, #, =等):
Yes:?????foo?=?1000??#?comment?????long_name?=?2??#?comment?that?should?not?be?aligned?????dictionary?=?{?????????"foo":?1,?????????"long_name":?2,?????????}No:?????foo???????=?1000??#?comment?????long_name?=?2?????#?comment?that?should?not?be?aligned?????dictionary?=?{?????????"foo"??????:?1,?????????"long_name":?2,?????????}
?????foo?=?1000??
#?comment
?????long_name?=?2??
#?comment?that?should?not?be?aligned
?????dictionary?=?{
?????????
"foo"
:?1,
?????????
"long_name"
:?2,
?????????}
No:
?????foo???????=?1000??
#?comment
?????long_name?=?2?????
#?comment?that?should?not?be?aligned
?????dictionary?=?{
?????????
"foo"
??????:?1,
?????????
"long_name"
:?2,
?????????}
Shebang
大部分.py文件不必以#!作為文件的開始. 根據(jù)?PEP-394?, 程序的main文件應(yīng)該以 #!/usr/bin/python2或者 #!/usr/bin/python3開始.
(譯者注: 在計算機科學(xué)中,?Shebang?(也稱為Hashbang)是一個由井號和嘆號構(gòu)成的字符串行(#!), 其出現(xiàn)在文本文件的第一行的前兩個字符. 在文件中存在Shebang的情況下, 類Unix操作系統(tǒng)的程序載入器會分析Shebang后的內(nèi)容, 將這些內(nèi)容作為解釋器指令, 并調(diào)用該指令, 并將載有Shebang的文件路徑作為該解釋器的參數(shù). 例如, 以指令#!/bin/sh開頭的文件在執(zhí)行時會實際調(diào)用/bin/sh程序.)
先用于幫助內(nèi)核找到Python解釋器, 但是在導(dǎo)入模塊時, 將會被忽略. 因此只有被直接執(zhí)行的文件中才有必要加入
注釋
確保對模塊, 函數(shù), 方法和行內(nèi)注釋使用正確的風(fēng)格
文檔字符串
Python有一種獨一無二的的注釋方式: 使用文檔字符串. 文檔字符串是包, 模塊, 類或函數(shù)里的第一個語句. 這些字符串可以通過對象的__doc__成員被自動提取, 并且被pydoc所用. (你可以在你的模塊上運行pydoc試一把, 看看它長什么樣). 我們對文檔字符串的慣例是使用三重雙引號”“”(?PEP-257?). 一個文檔字符串應(yīng)該這樣組織: 首先是一行以句號, 問號或驚嘆號結(jié)尾的概述(或者該文檔字符串單純只有一行). 接著是一個空行. 接著是文檔字符串剩下的部分, 它應(yīng)該與文檔字符串的第一行的第一個引號對齊. 下面有更多文檔字符串的格式化規(guī)范.
模塊
每個文件應(yīng)該包含一個許可樣板. 根據(jù)項目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適的樣板.
函數(shù)和方法
下文所指的函數(shù),包括函數(shù), 方法, 以及生成器.
一個函數(shù)必須要有文檔字符串, 除非它滿足以下條件:
外部不可見
非常短小
簡單明了
文檔字符串應(yīng)該包含函數(shù)做什么, 以及輸入和輸出的詳細描述. 通常, 不應(yīng)該描述”怎么做”, 除非是一些復(fù)雜的算法. 文檔字符串應(yīng)該提供足夠的信息, 當(dāng)別人編寫代碼調(diào)用該函數(shù)時, 他不需要看一行代碼, 只要看文檔字符串就可以了. 對于復(fù)雜的代碼, 在代碼旁邊加注釋會比使用文檔字符串更有意義.
關(guān)于函數(shù)的幾個方面應(yīng)該在特定的小節(jié)中進行描述記錄, 這幾個方面如下文所述. 每節(jié)應(yīng)該以一個標題行開始. 標題行以冒號結(jié)尾. 除標題行外, 節(jié)的其他內(nèi)容應(yīng)被縮進2個空格.
Args:
列出每個參數(shù)的名字, 并在名字后使用一個冒號和一個空格, 分隔對該參數(shù)的描述.如果描述太長超過了單行80字符,使用2或者4個空格的懸掛縮進(與文件其他部分保持一致). 描述應(yīng)該包括所需的類型和含義. 如果一個函數(shù)接受*foo(可變長度參數(shù)列表)或者**bar (任意關(guān)鍵字參數(shù)), 應(yīng)該詳細列出*foo和**bar.
Returns: (或者 Yields: 用于生成器)
描述返回值的類型和語義. 如果函數(shù)返回None, 這一部分可以省略.
Raises:
列出與接口有關(guān)的所有異常.
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
????
"""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
類
類應(yīng)該在其定義下有一個用于描述該類的文檔字符串. 如果你的類有公共屬性(Attributes), 那么文檔中應(yīng)該有一個屬性(Attributes)段. 并且應(yīng)該遵守和函數(shù)參數(shù)相同的格式
class?SampleClass(object):????"""Summary?of?class?here.????Longer?class?information....????Longer?class?information....????Attributes:????????likes_spam:?A?boolean?indicating?if?we?like?SPAM?or?not.????????eggs:?An?integer?count?of?the?eggs?we?have?laid.????"""????def?__init__(self,?likes_spam=False):????????"""Inits?SampleClass?with?blah."""????????self.likes_spam?=?likes_spam????????self.eggs?=?0????def?public_method(self):????????"""Performs?operation?blah."""
????
"""Summary?of?class?here.
????Longer?class?information....
????Longer?class?information....
????Attributes:
????????likes_spam:?A?boolean?indicating?if?we?like?SPAM?or?not.
????????eggs:?An?integer?count?of?the?eggs?we?have?laid.
????"""
????
def
?
__init__
(self,?likes_spam=False)
:
????????
"""Inits?SampleClass?with?blah."""
????????self.likes_spam?=?likes_spam
????????self.eggs?=?
0
????
def
?
public_method
(self)
:
????????
"""Performs?operation?blah."""
塊注釋和行注釋
最需要寫注釋的是代碼中那些技巧性的部分. 如果你在下次?代碼審查?的時候必須解釋一下, 那么你應(yīng)該現(xiàn)在就給它寫注釋. 對于復(fù)雜的操作, 應(yīng)該在其操作開始前寫上若干行注釋. 對于不是一目了然的代碼, 應(yīng)在其行尾添加注釋.
# 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 if i is 0 or a power of 2.
為了提高可讀性, 注釋應(yīng)該至少離開代碼2個空格.
另一方面, 絕不要描述代碼. 假設(shè)閱讀代碼的人比你更懂Python, 他只是不知道你的代碼要做什么.
# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1
類
如果一個類不繼承自其它類, 就顯式的從object繼承. 嵌套類也一樣.
Yes:?class?SampleClass(object):?????????pass?????class?OuterClass(object):?????????class?InnerClass(object):?????????????pass?????class?ChildClass(ParentClass):?????????"""Explicitly?inherits?from?another?class?already."""No:?class?SampleClass:????????pass????class?OuterClass:????????class?InnerClass:????????????pass
?????????
pass
?????
class
?
OuterClass
(object)
:
?????????
class
?
InnerClass
(object)
:
?????????????
pass
?????
class
?
ChildClass
(ParentClass)
:
?????????
"""Explicitly?inherits?from?another?class?already."""
No:?
class
?
SampleClass
:
????????
pass
????
class
?
OuterClass
:
????????
class
?
InnerClass
:
????????????
pass
繼承自?
object
?是為了使屬性(properties)正常工作, 并且這樣可以保護你的代碼, 使其不受?PEP-3000?的一個特殊的潛在不兼容性影響. 這樣做也定義了一些特殊的方法, 這些方法實現(xiàn)了對象的默認語義, 包括?
__new__,
?
__init__,
?
__delattr__,
?
__getattribute__,
?
__setattr__,
?
__hash__,
?
__repr__,
?
and
?
__str__
?.
字符串
即使參數(shù)都是字符串, 使用%操作符或者格式化方法格式化字符串. 不過也不能一概而論, 你需要在+和%之間好好判定.
Yes:?x?=?a?+?b?????x?=?'%s,?%s!'?%?(imperative,?expletive)?????x?=?'{},?{}!'.format(imperative,?expletive)?????x?=?'name:?%s;?score:?%d'?%?(name,?n)?????x?=?'name:?{};?score:?{}'.format(name,?n)No:?x?=?'%s%s'?%?(a,?b)??#?use?+?in?this?case????x?=?'{}{}'.format(a,?b)??#?use?+?in?this?case????x?=?imperative?+?',?'?+?expletive?+?'!'????x?=?'name:?'?+?name?+?';?score:?'?+?str(n)
'%s,?%s!'
?%?(imperative,?expletive)
?????x?=?
'{},?{}!'
.format(imperative,?expletive)
?????x?=?
'name:?%s;?score:?%d'
?%?(
name
,?n)
?????x?=?
'name:?{};?score:?{}'
.format(
name
,?n)
No:?x?=?
'%s%s'
?%?(a,?b)??#?use?+?
in
?this?
case
????x?=?
'{}{}'
.format(a,?b)??#?use?+?
in
?this?
case
????x?=?imperative?+?
',?'
?+?expletive?+?
'!'
????x?=?
'name:?'
?+?
name
?+?
';?score:?'
?+?str(n)
避免在循環(huán)中用+和+=操作符來累加字符串. 由于字符串是不可變的, 這樣做會創(chuàng)建不必要的臨時對象, 并且導(dǎo)致二次方而不是線性的運行時間. 作為替代方案, 你可以將每個子串加入列表, 然后在循環(huán)結(jié)束后用?
.join
?連接列表. (也可以將每個子串寫入一個?
cStringIO.StringIO
?緩存中.)
Yes:?items?=?['
']?????for?last_name,?first_name?in?employee_list:?????????items.append('
%s,?%s
'?%?(last_name,?first_name))?????items.append('
')?????employee_table?=?''.join(items)No:?employee_table?=?'
'????for?last_name,?first_name?in?employee_list:????????employee_table?+=?'
%s,?%s
'?%?(last_name,?first_name)????employee_table?+=?'
'
?????
for
?last_name,?first_name?
in
?employee_list:
?????????items.append(
'
%s,?%s
'?%?(last_name,?first_name))
?????items.append(
'
')
?????employee_table?=?
''.join(items)
No:?employee_table?=?
'
for
in
'
%s,?%s
'?%?(last_name,?first_name)
'
'
????
?last_name,?first_name?
?employee_list:
????????employee_table?+=?
????employee_table?+=?
'
在同一個文件中, 保持使用字符串引號的一致性. 使用單引號’或者雙引號”之一用以引用字符串, 并在同一文件中沿用. 在字符串內(nèi)可以使用另外一種引號, 以避免在字符串中使用. GPyLint已經(jīng)加入了這一檢查.
(譯者注:GPyLint疑為筆誤, 應(yīng)為PyLint.)
Yes:?????Python('Why?are?you?hiding?your?eyes?')?????Gollum("I'm?scared?of?lint?errors.")?????Narrator('"Good!"?thought?a?happy?Python?reviewer.')No:?????Python("Why?are?you?hiding?your?eyes?")?????Gollum('The?lint.?It?burns.?It?burns?us.')?????Gollum("Always?the?great?lint.?Watching.?Watching.")
'Why?are?you?hiding?your?eyes?')
?????Gollum(
"I'm?scared?of?lint?errors."
)
?????Narrator(
'"Good!"?thought?a?happy?Python?reviewer.')
No:
?????Python(
"Why?are?you?hiding?your?eyes?"
)
?????Gollum(
'The?lint.?It?burns.?It?burns?us.')
?????Gollum(
"Always?the?great?lint.?Watching.?Watching."
)
為多行字符串使用三重雙引號”“”而非三重單引號’‘’. 當(dāng)且僅當(dāng)項目中使用單引號’來引用字符串時, 才可能會使用三重’‘’為非文檔字符串的多行字符串來標識引用. 文檔字符串必須使用三重雙引號”“”. 不過要注意, 通常用隱式行連接更清晰, 因為多行字符串與程序其他部分的縮進方式不一致.
Yes:????print?("This?is?much?nicer.\n"???????????"Do?it?this?way.\n")No:??????print?"""This?is?pretty?ugly.??Don't?do?this.??"""
print
?(
"This?is?much?nicer.\n"
???????????
"Do?it?this?way.\n"
)
No:
??????
print
?
"""This?is?pretty?ugly.
??Don't?do?this.
??"""
文件和sockets
在文件和sockets結(jié)束時, 顯式的關(guān)閉它.
除文件外, sockets或其他類似文件的對象在沒有必要的情況下打開, 會有許多副作用, 例如:
-
它們可能會消耗有限的系統(tǒng)資源, 如文件描述符. 如果這些資源在使用后沒有及時歸還系統(tǒng), 那么用于處理這些對象的代碼會將資源消耗殆盡.
-
持有文件將會阻止對于文件的其他諸如移動、刪除之類的操作.
-
僅僅是從邏輯上關(guān)閉文件和sockets, 那么它們?nèi)匀豢赡軙黄涔蚕淼某绦蛟跓o意中進行讀或者寫操作. 只有當(dāng)它們真正被關(guān)閉后, 對于它們嘗試進行讀或者寫操作將會拋出異常, 并使得問題快速顯現(xiàn)出來.
而且, 幻想當(dāng)文件對象析構(gòu)時, 文件和sockets會自動關(guān)閉, 試圖將文件對象的生命周期和文件的狀態(tài)綁定在一起的想法, 都是不現(xiàn)實的. 因為有如下原因:
-
沒有任何方法可以確保運行環(huán)境會真正的執(zhí)行文件的析構(gòu). 不同的Python實現(xiàn)采用不同的內(nèi)存管理技術(shù), 比如延時垃圾處理機制. 延時垃圾處理機制可能會導(dǎo)致對象生命周期被任意無限制的延長.
-
對于文件意外的引用,會導(dǎo)致對于文件的持有時間超出預(yù)期(比如對于異常的跟蹤, 包含有全局變量等).
推薦使用?“with”語句?以管理文件:
with?open("hello.txt")?as?hello_file:????for?line?in?hello_file:????????print?line
"hello.txt"
)?
as
?hello_file:
????
for
?line?
in
?hello_file:
????????
print
?line
對于不支持使用”with”語句的類似文件的對象,使用 contextlib.closing():
import?contextlibwith?contextlib.closing(urllib.urlopen("http://www.python.org/"))?as?front_page:????for?line?in?front_page:????????print?line
with
?contextlib.closing(urllib.urlopen(
"http://www.python.org/"
))?
as
?front_page:
????
for
?line?
in
?front_page:
????????
print
?line
Legacy AppEngine 中Python 2.5的代碼如使用”with”語句, 需要添加 “from __future__ import with_statement”.
TODO注釋
為臨時代碼使用TODO注釋, 它是一種短期解決方案. 不算完美, 但夠好了.
TODO注釋應(yīng)該在所有開頭處包含”TODO”字符串, 緊跟著是用括號括起來的你的名字, email地址或其它標識符. 然后是一個可選的冒號. 接著必須有一行注釋, 解釋要做什么. 主要目的是為了有一個統(tǒng)一的TODO格式, 這樣添加注釋的人就可以搜索到(并可以按需提供更多細節(jié)). 寫了TODO注釋并不保證寫的人會親自解決問題. 當(dāng)你寫了一個TODO, 請注上你的名字.
#?TODO(kl@gmail.com):?Use?a?"*"?here?for?string?repetition.#?TODO(Zeke)?Change?this?to?use?relations.
"*"
?here?
for
?string?repetition.
#?TODO(Zeke)?Change?
this
?to?use?relations.
如果你的TODO是”將來做某事”的形式, 那么請確保你包含了一個指定的日期(“2009年11月解決”)或者一個特定的事件(“等到所有的客戶都可以處理XML請求就移除這些代碼”).
導(dǎo)入格式
每個導(dǎo)入應(yīng)該獨占一行
Yes:?import?os?????import?sysNo:??import?os,?sys
?????
import
?sys
No:??
import
?os,?sys
導(dǎo)入總應(yīng)該放在文件頂部, 位于模塊注釋和文檔字符串之后, 模塊全局變量和常量之前. 導(dǎo)入應(yīng)該按照從最通用到最不通用的順序分組:
-
標準庫導(dǎo)入
-
第三方庫導(dǎo)入
-
應(yīng)用程序指定導(dǎo)入
每種分組中, 應(yīng)該根據(jù)每個模塊的完整包路徑按字典序排序, 忽略大小寫.
import?foofrom?foo?import?barfrom?foo.bar?import?bazfrom?foo.bar?import?Quuxfrom?Foob?import?ar
from
?foo?
import
?bar
from
?foo.bar?
import
?baz
from
?foo.bar?
import
?Quux
from
?Foob?
import
?ar
語句
通常每個語句應(yīng)該獨占一行
不過, 如果測試結(jié)果與測試語句在一行放得下, 你也可以將它們放在同一行. 如果是if語句, 只有在沒有else時才能這樣做. 特別地, 絕不要對?
try/except
?這樣做, 因為try和except不能放在同一行.
Yes:??if?foo:?bar(foo)No:??if?foo:?bar(foo)??else:???baz(foo)??try:???????????????bar(foo)??except?ValueError:?baz(foo)??try:??????bar(foo)??except?ValueError:?baz(foo)
??
if
?foo:?bar(foo)
No:
??
if
?foo:?bar(foo)
??
else
:???baz(foo)
??
try
:???????????????bar(foo)
??
except
?ValueError:?baz(foo)
??
try
:
??????bar(foo)
??
except
?ValueError:?baz(foo)
訪問控制
在Python中, 對于瑣碎又不太重要的訪問函數(shù), 你應(yīng)該直接使用公有變量來取代它們, 這樣可以避免額外的函數(shù)調(diào)用開銷. 當(dāng)添加更多功能時, 你可以用屬性(property)來保持語法的一致性.
(譯者注: 重視封裝的面向?qū)ο蟪绦騿T看到這個可能會很反感, 因為他們一直被教育: 所有成員變量都必須是私有的! 其實, 那真的是有點麻煩啊. 試著去接受Pythonic哲學(xué)吧)
另一方面, 如果訪問更復(fù)雜, 或者變量的訪問開銷很顯著, 那么你應(yīng)該使用像?
get_foo()
?和?
set_foo()
?這樣的函數(shù)調(diào)用. 如果之前的代碼行為允許通過屬性(property)訪問 , 那么就不要將新的訪問函數(shù)與屬性綁定. 這樣, 任何試圖通過老方法訪問變量的代碼就沒法運行, 使用者也就會意識到復(fù)雜性發(fā)生了變化.
命名
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.
應(yīng)該避免的名稱
單字符名稱, 除了計數(shù)器和迭代器.
包/模塊名中的連字符(-)
雙下劃線開頭并結(jié)尾的名稱(Python保留, 例如__init__)
命名約定
所謂”內(nèi)部(Internal)”表示僅模塊內(nèi)可用, 或者, 在類內(nèi)是保護或私有的.
用單下劃線(_)開頭表示模塊變量或函數(shù)是protected的(使用from module import *時不會包含).
用雙下劃線(__)開頭的實例變量或方法表示類內(nèi)私有.
將相關(guān)的類和頂級函數(shù)放在同一個模塊里. 不像Java, 沒必要限制一個類一個模塊.
對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal風(fēng)格), 但是模塊名應(yīng)該用小寫加下劃線的方式(如lower_with_under.py). 盡管已經(jīng)有很多現(xiàn)存的模塊使用類似于CapWords.py這樣的命名, 但現(xiàn)在已經(jīng)不鼓勵這樣做, 因為如果模塊名碰巧和類名一致, 這會讓人困擾.
Python之父Guido推薦的規(guī)范
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 |
|
Main
即使是一個打算被用作腳本的文件, 也應(yīng)該是可導(dǎo)入的. 并且簡單的導(dǎo)入不應(yīng)該導(dǎo)致這個腳本的主功能(main functionality)被執(zhí)行, 這是一種副作用. 主功能應(yīng)該放在一個main()函數(shù)中.
在Python中, pydoc以及單元測試要求模塊必須是可導(dǎo)入的. 你的代碼應(yīng)該在執(zhí)行主程序前總是檢查?
if
?
__name__
?
==
?
'__main__'
?, 這樣當(dāng)模塊被導(dǎo)入時主程序就不會被執(zhí)行.
def?main():??????...if?__name__?==?'__main__':????main()
??????...
if
?__name__?==?
'__main__'
:
????main()
所有的頂級代碼在模塊導(dǎo)入時都會被執(zhí)行. 要小心不要去調(diào)用函數(shù), 創(chuàng)建對象, 或者執(zhí)行那些不應(yīng)該在使用pydoc時執(zhí)行的操作.
以上是google建議大家的Python 編碼規(guī)范。
END歷史閱讀開發(fā)者技術(shù)前線?,匯集技術(shù)前線快訊和關(guān)注行業(yè)趨勢,大廠干貨,是開發(fā)者經(jīng)歷和成長的優(yōu)秀指南。
Python 3.8 ?正式發(fā)布,新特性全面解讀
Python 學(xué)習(xí)路線思維導(dǎo)圖, 經(jīng)典收藏!
Kotlin 新版來了,支持跨平臺!




更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
