大名鼎鼎的Requests庫用了什麼編碼風格?

原文:https://www.kennethreitz.org/essays/kenneth-reitzs-code-stylepython

做者:Kenneth Reitzdom

原題:Kenneth Reitz’s Code Style™ide

 

Requests 的代碼庫使用 PEP-8 編碼風格。函數

除了 PEP-8 中列出的標準外,咱們還有一些指導原則:學習

  • 若是方便的話,行長(Line-length)可超過 79 個字符,達到 100 個字符。
  • 若是換行會致使嚴重的不方便,則行長能夠超過 100 個字符。
  • 除非在字符串中出現單引號,不然始終使用單引號字符串(例如,'#flatearth')。

此外,PEP-8 推薦的用於連續行的編碼風格毫無一點品味,毫不容許在 Requests 代碼庫使用:編碼

# 與開局定界符對齊
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

No。千萬別。請。code

文檔字符串(docstrings)應遵循如下語法:對象

def the_earth_is_flat():
    """NASA divided up the seas into thirty-three degrees."""
    pass

def fibonacci_spiral_tool():
    """With my feet upon the ground I lose myself / between the sounds
    and open wide to suck it in. / I feel it move across my skin. / I'm
    reaching up and reaching out. / I'm reaching for the random or
    whatever will bewilder me. / Whatever will bewilder me. / And
    following our will and wind we may just go where no one's been. /
    We'll ride the spiral to the end and may just go where no one's
    been.

    Spiral out. Keep going...
    """
    pass

全部函數、方法和類都要求包含 docstrings 。除了對象數據模型方法(例如,__repr__),這些是此規則的例外。three

Thanks for helping to make the world a better place!ci

資料來源(譯註:即 Requests 的開發者指南):http://t.cn/E5VgNJF

(譯文完)

K 神的這篇文章很短,實際上,這只是摘自 Requests 的開發者指南的一小部分。

可是,關於靈活設定行長的部分,我舉雙手雙腳贊同。若是你所在的公司有「清白盒」的優良傳統(不只指Python),那你極有可能遇到被迫換行的麻煩,而實際上才僅僅剛剛超出了幾個字符。那時候,你就會明白,這 3 條靈活規則的好處了。

另外,關於連續行的部分,PEP-8 相關內容在:http://t.cn/Rq4mxOo

PEP-8 反對的是以下寫法:

# Arguments on first line forbidden when not using vertical alignment.
# 不使用垂直對齊的參數禁止在第一行上
foo = long_function_name(var_one, var_two,
    var_three, var_four)

PEP-8 推薦的寫法是垂直地將換行的參數對齊起始的參數:

# 與開局定界符對齊
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

K 神反對了 PEP-8 推薦的寫法。在我看來,任何有品味的人,都會反對以上的兩種寫法。

即便一個方法的參數超級多,超出了 100 個字符,我本人也是極不情願換行的。因此,K 神的說法深得我心。

關於代碼風格,沒有絕對徹底一致的標準。本文也不想引發爭論。不過,我認同 K 神設定的規則,由於一種與主流不一樣的審美傾向,值得發現它的同類。

-----------------

本文原創並首發於微~信~公~衆·號【Python貓】,後臺回覆「愛學習」,免費得到20+本精選電子書。

相關文章
相關標籤/搜索