Python 之禅
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 之禅中文译本。因此,这里是我们自行翻译选定的译本,可能在理解上有不到位的地方,也可能文字润色不够精要,大家也可以参考其他的译本形成你的理解和润色版本。
- 美观胜于丑陋 ( 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! )