什么样的Python代码是最漂亮的?

由于Python语言的格式框架也是语法元素的一部分,且语法中没有过多的控制格式符号,因此,不经过任何要求的Python源程序都具有一定的可读性。进一步,什么样的代码是漂亮的?Tim Peters从哲学层面给出了一个非常优美的回答,被称为Python之禅。

  1. >>> import this
  2. The Zen of Python, by Tim Peters
  3. Beautiful is better than ugly.
  4. Explicit is better than implicit.
  5. Simple is better than complex.
  6. Complex is better than complicated.
  7. Flat is better than nested.
  8. Sparse is better than dense.
  9. Readability counts.
  10. Special cases aren't special enough to break the rules.
  11. Although practicality beats purity.
  12. Errors should never pass silently.
  13. Unless explicitly silenced.
  14. In the face of ambiguity, refuse the temptation to guess.
  15. There should be one-- and preferably only one --obvious way to do it.
  16. Although that way may not be obvious at first unless you're Dutch.
  17. Now is better than never.
  18. Although never is often better than *right* now.
  19. If the implementation is hard to explain, it's a bad idea.
  20. If the implementation is easy to explain, it may be a good idea.
  21. Namespaces are one honking great idea -- let's do more of those!

翻译后的理解:

  • 优美胜于丑陋
  • 明了胜于隐晦
  • 简洁胜于复杂
  • 复杂胜于凌乱
  • 扁平胜于嵌套
  • 间隔胜于紧凑
  • 可读性很重要
  • 即便假借特例的实用性之名,也不要违背上述规则
  • 除非你确定需要,任何错误都应该有对应
  • 当存在多种可能,不要尝试去猜测
  • 只要你不是Guido,对于问题尽量找一种,最好是唯一明显的解决方案
  • 做也许好过不做,但不假思索就动手还是不如不做
  • 如果你无法向人描述你的实现方案,那肯定不是一个好方案
  • 如果实现方案容易解释,可能是个好方案
  • 命名空间是绝妙的理念,要多运用