What is the Zen of Python and what are its most important principles?
The Zen of Python (PEP 20) is a collection of 19 guiding principles for writing Python. Access it with import this. The most impactful principles for daily coding:
- Beautiful is better than ugly - Write clean, readable code.
- Explicit is better than implicit - Do not hide behavior; make intent clear.
- Simple is better than complex - Choose the simplest solution that works.
- Readability counts - Code is read far more often than written.
- There should be one-- and preferably only one --obvious way to do it - Python prefers one clear approach.
- Errors should never pass silently - Handle exceptions explicitly.
- In the face of ambiguity, refuse the temptation to guess - Be explicit.
- Flat is better than nested - Avoid deep nesting; use early returns.
- If the implementation is hard to explain, it's a bad idea - Simplicity wins.
import this # Prints the Zen of Python
Key takeaways:
- Readability > cleverness
- Explicit > implicit
- Simple > complex
- Flat > nested
- One obvious way to do it
# import this # Prints the Zen of Python
# Principle: Beautiful is better than ugly
# Ugly
result = dict([(k,v) for k,v in zip(keys,vals)])
# Beautiful
result = dict(zip(keys, vals))
# Principle: Explicit is better than implicit
# Implicit (what does * do here?)
from math import *
# Explicit
from math import sqrt, pi
# Principle: Simple is better than complex
# Complex
def is_even(n):
return True if n % 2 == 0 else False
# Simple
def is_even(n):
return n % 2 == 0
# Principle: Flat is better than nested
# Nested
def process(data):
if data:
if data.get('valid'):
if data.get('type') == 'user':
return handle_user(data)
return None
# Flat (early returns)
def process(data):
if not data:
return None
if not data.get('valid'):
return None
if data.get('type') != 'user':
return None
return handle_user(data)
# Principle: Errors should never pass silently
# Bad: silently ignoring errors
try:
value = int(user_input)
except:
pass
# Good: handle explicitly
try:
value = int(user_input)
except ValueError:
print(f"Invalid number: {user_input}")
value = 0
# Principle: Readability counts
# Clever but unreadable
result = [x for x in (y.strip() for y in open('f.txt')) if x and not x.startswith('#')]
# Readable
with open('f.txt') as f:
result = []
for line in f:
line = line.strip()
if line and not line.startswith('#'):
result.append(line)
- •Readability and simplicity are core Python values
- •Prefer explicit imports, explicit error handling, and clear variable names
- •Use early returns to flatten nested conditionals
- •Never use bare except:; always catch specific exceptions
- •If it is hard to explain, simplify it
- •The Zen of Python has intentional contradictions (e.g., 'practicality beats purity')
- •'One obvious way' does not mean there is literally one way; it means prefer the conventional way
- •Clever one-liners are not Pythonic if they sacrifice readability