Python 之禪

Wxy發表於2021-02-17

Python 之禪Zen of Python最早由 Tim Peters 於 1999 年發表於 Python 郵件列表中,它包含了影響 Python 程式語言設計的 19 條軟體編寫原則。在最初及後來的一些版本中,一共包含 20 條,其中第 20 條是“這一條留空(...)請 Guido 來填寫”。這留空的一條從未公佈也可能並不存在。

Python 之禪作為一個資訊條款也被錄入 Python 增強建議Python Enhancement Proposals(PEP)的第 20 條,在 Python 語言的官方網站也能找到

此外,關於 Python 之禪,還有一件趣事。在 2001 召開第十屆國際 Python 峰會(IPC 10,Pycon 的前身)前夕,會議主辦方希望定製一件 T 恤,並絞盡腦汁地從投稿的標語中選擇了一條 “import this”。然後,他們決定將這個語句實現在 Python 直譯器中,於是將 Python 之禪的內容進行簡單加密後放入到了 Python 2.2.1 中的 this.py 庫當中。如果你在 Python 的直譯器中輸入 import this ,就會顯示出來:

>>> import this;
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

作為 Python 之禪系列文章的總結,我在下面重新整理並連結了之前的各篇文章。對於 Python 之禪的理解大家各有不同,目前也有幾個不同的中文翻譯版本。為了避免雷同,我們在翻譯這系列文章時有意沒有參考現有的 Python 之禪中文譯本。因此,這裡是我們自行翻譯選定的譯本,可能在理解上有不到位的地方,也可能文字潤色不夠精要,大家也可以參考其他的譯本形成你的理解和潤色版本。

  1. 美觀勝於醜陋Beautiful is better than ugly.
  2. 明確勝於隱晦Explicit is better than implicit.
  3. 簡單勝過複雜Simple is better than complex.
  4. 複雜勝過錯綜複雜Complex is better than complicated.
  5. 扁平勝過巢狀Flat is better than nested.
  6. 稀疏勝過密集Sparse is better than dense.
  7. 可讀性很重要Readability counts.
  8. 特殊情況不足以違反規則Special cases aren't special enough to break the rules.
  9. 雖然,實用性勝過純潔性Although practicality beats purity.
  10. 錯誤絕不應該悄悄傳遞Errors should never pass silently.
  11. 除非顯式消除Unless explicitly silenced.
  12. 面對歧義In the face of ambiguity, 要拒絕猜測的誘惑refuse the temptation to guess.
  13. 儘量找一種There should be one - 最好是唯一一種明顯的解決方案and preferably only one - obvious way to do it.
  14. 雖然這種方式一開始可能並不明顯Although that way may not be obvious at first. (除非你是荷蘭人)unless you're Dutch.
  15. 現在有總比永遠沒有好Now is better than never.
  16. 雖然將來總比現在好Although never is often better than right now.
  17. 如果一個實現難以解釋If the implementation is hard to explain, 那就是個壞思路it's a bad idea.
  18. 如果一個實現易於解釋 If the implementation is easy to explain, 那它可能是一個好思路it may be a good idea.
  19. 名稱空間是一個非常棒的想法Namespaces are one honking great idea— 讓我們做更多的名稱空間!let's do more of those!
Python 之禪

相關文章