Google Python Style Guide

閱讀Google Python Style Guide的時候,意識到有一些問題確實會很容易犯錯。記錄下來以備復習。

關于字符串的使用

使用format和%操作符來格式化和拼接字符串。不要使用+。因為+會產生很多不必要零時對象,憑白增加了系統的負載。

下面這些是正確的做法:

     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)

當然,單純的兩個字符串拼接還是支持用a+b的。其他的都應該使用format和%。

注釋的正確寫法

下面是方法的DocString :

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

類的DocString :

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."""

對于一句話的注釋,應該給出兩個空格。

# 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

符號間隔

python比較特殊的地方在于,這個符號','后面要加一個空格。比如:

spam(ham[1], {eggs: 2}, [])
x, y = y, x

還有就是,在給參數賦默認值的時候,等號無需空格分開:

def complex(real, imag=0.0): return magic(r=real, i=imag)

不用刻意去對齊注釋,下面這樣是不對的,會帶來維護上的麻煩。

  foo       = 1000  # comment
  long_name = 2     # comment that should not be aligned

  dictionary = {
      'foo'      : 1,
      'long_name': 2,
  }

空行

對于類和頂級的方法,需要用雙行空行包圍,對于類中的成員方法,用單行包圍。注意,是包圍哦。

括號

python里面括號是有意義的,代表一個元組,不要隨便在return語句里套括號,不然你返回的就是也一個元組了。

參數值

如果有默認參數值的情況,使用none會比較好:

    def foo(a, b=None):
         if b is None:
             b = []

當你使用“可變”的對象作為函數中作為默認參數時會往往引起問題。因為在這種情況下參數可以在不創建新對象的情況下進行修改,例如 list dict。

>>> def function(data=[]):  
...     data.append(1)  
...     return data  
...  
>>> function()  
[1]  
>>> function()  
[1, 1]  
>>> function()  
[1, 1, 1]  

像你所看到的那樣,list變得越來越長。如果你仔細地查看這個list。你會發現list一直是同一個對象。

原因很簡單: 在每次函數調用的時候,函數一直再使用同一個list對象。這么使用引起的變化,非常“sticky”

像其他人所提到的那樣,用一個占位符來替代可以修改的默認值。None

def myfunc(value=None):  
    if value is None:  
        value = []  
    # modify value here 
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容