PYTHON
The Zen of Python, with the examples I corrected
In 2024 I posted the Zen of Python aphorisms with a tip and an example for each. Looking back, several examples didn't show what the aphorism says, and two contradicted each other. This is the corrected version.
In February 2024 I posted the Zen of Python aphorisms here, each with a tip and a code example. Rereading it,
several examples didn’t show what the aphorism says. Two contradicted each other: math.factorial appeared as the
“simple” option in one item and as the “complicated” one in the next. Some blocks also had a one-space indent, which
is an error in Python.
This version keeps the aphorisms that can be shown with an honest example.
Where it comes from
The text is by Tim Peters, published as PEP 20. It shows up in the interpreter itself:
import this
The PEP speaks of 20 aphorisms, only 19 of which were written down.
Beautiful is better than ugly
In practice, it’s almost always about names. The code does the same thing; what changes is how much it tells the reader.
# ugly
def calc(l):
t = 0
for i in l:
t += i[1] * i[2]
return t
# beautiful
def total_do_pedido(itens):
return sum(item.preco * item.quantidade for item in itens)
Explicit is better than implicit
The classic example is import *. Whoever reads the file doesn’t know where each name came from, and one module
can overwrite another’s name without warning.
# implicit
from os.path import *
caminho = join(pasta, nome)
# explicit
from os.path import join
caminho = join(pasta, nome)
Simple is better than complex, and complex is better than complicated
The two go together. Simple is using what the language already offers:
# complex
total = 0
for valor in valores:
total = total + valor
# simple
total = sum(valores)
Complicated is when the solution has more parts than the problem calls for. Tracking the index by hand to know each
item’s position is a common case, and enumerate solves it:
# complicated
i = 0
for nome in nomes:
print(i, nome)
i += 1
# simpler
for i, nome in enumerate(nomes):
print(i, nome)
Flat is better than nested
Each if inside another pushes the main rule to the right. Leaving the function early for the cases you don’t care
about keeps the main path straight:
# nested
def enviar(pedido):
if pedido:
if pedido.pago:
if not pedido.enviado:
despachar(pedido)
# flat
def enviar(pedido):
if not pedido or not pedido.pago or pedido.enviado:
return
despachar(pedido)
Sparse is better than dense
Fitting on one line isn’t a merit. A list comprehension with two conditions and a transformation is already asking to be broken into named steps:
# dense
emails = [u.email.lower() for u in usuarios if u.ativo and u.email and not u.email.endswith("@teste.com")]
# sparse
def email_valido(usuario):
return usuario.ativo and usuario.email and not usuario.email.endswith("@teste.com")
emails = [u.email.lower() for u in usuarios if email_valido(u)]
Errors should never pass silently
Unless explicitly silenced, the aphorism continues. A bare except swallows everything, including the error you
didn’t foresee:
# silence
try:
config = carregar_config()
except:
pass
# on purpose, and only the expected error
try:
config = carregar_config()
except FileNotFoundError:
config = CONFIG_PADRAO
In the face of ambiguity, refuse the temptation to guess
Python itself follows this one. Adding text to a number becomes neither "11" nor 2: it becomes an error, and
whoever wrote it decides what they meant.
>>> "1" + 1
TypeError: can only concatenate str (not "int") to str
>>> int("1") + 1
2
If the implementation is hard to explain, it’s a bad idea
It works as a test before handing over a piece of code: if explaining what it does takes more than a paragraph, you can almost always split the function or swap the trick for something obvious.
References
Who writes this
Eduardo Lira
Software developer in Rio de Janeiro. I started this blog in 2012, in technical support at a hosting company, writing down the fixes for the problems that came up every day. Today I work at Sofis Tecnologia, on critical healthcare systems and SQL Server database migrations.