PEP 20 – The Zen of Python is a set of principles that define Python’s design philosophy. Written by Tim Peters, they guide us toward simple, explicit, and readable code.
Definition
PEP 20 (known as The Zen of Python) is a list of maxims that summarize best practices and the aesthetic values of Python. You can display it in the interpreter with:
import this
Key principles (selection)
- Beautiful is better than ugly: code should be clean and pleasant to read.
- Simple is better than complex: prefer straightforward solutions.
- Explicit is better than implicit: avoid ambiguity and “magic”.
- Readability counts: readability is a priority.
- There should be one— and preferably only one— obvious way to do it: consistency and clear paths.
- Errors should never pass silently (unless explicitly silenced): handle exceptions deliberately.
- Namespaces are one honking great idea — let’s do more of those!: organize code and avoid name clashes.
See the full list of maxims
- 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!
Practical application
Example of simplicity and readability (Readability counts):
# Less clear (too much "magic")
vals = [1, 2, 2, 3, 4]
u = []
[u.append(v) for v in vals if v not in u]
# Simpler and more explicit (preferable, PEP 20)
vals = [1, 2, 2, 3, 4]
u = list(set(vals))
Context & authorship
The Zen of Python was written by Tim Peters. “PEP” stands for Python Enhancement Proposal.