The Zen of Python - An In-depth Explanation

Subscribe to my newsletter and never miss my upcoming articles

The Zen of Python by Tim Peters are guidelines for how your Python code should be written. Your code doesn’t have to follow these guidelines, but it's good to keep them in mind.

>>> 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!"""

Beautiful is better than ugly

I believe this is already self-explanatory but I'll still go over this. It simply says that beautiful code is better than ugly code. Writing a program that once read is easily understood is better than one that'll give the reader some time to figure out. Of course, not every script needs to be beautiful, and beauty is subjective, but much of Python’s popularity is a result of being so easy to work with.

# code 1

file = "lyrics.txt"
open("disordered.txt", "w").write("\n".join(map(lambda x: x[::-1], open(file, "r").read().split("\n")[::-1])))
# code 2

file = "lyrics.txt"
# first read the input file
lyrics = open(file, "r").read()

# split the lyrics into lines and reorder it in reverse form
lyrics = lyrics.split("\n")[::-1]

# reverse each line in the lyrics
reverse = lambda x: x[::-1]
lyrics = list(map(reverse, lyrics))

# merge the new lyrics together
lyrics = "\n".join(lyrics)

# save the file
open("disordered.txt", "w").write(lyrics)

which of these codes do you prefer and feel is easy to work with?

Explicit is better than implicit

This means that you should avoid hiding your code functionality behind obscure language features that require familiarity to fully understand. Let your code be readable by a stranger who knows nothing about you or your program. Refer back to the code above

Simple is better than complex

This tells us that when building anything it can be done using simple techniques. When presented with a simple problem, solve it with a simple solution and when presented with a complex problem, break it into simpler parts, and solve them with simple solutions.

Complex is better than complicated

Going back to the previous rule, some problems don't have a simple solution to solving them and in such cases, you'll have to use a complex solution. But this is better than using a complicated one. Prefer simplicity to complexity, but know the limits of simplicity.

Flat is better than nested

Programmers love to organize things into categories, especially categories that contain subcategories that contain other sub-subcategories. It’s okay to have code in just one top-layer module or class instead of splitting up across multiple submodules or subclasses. If you make packages and modules that require code like import, then you’re making your code too complicated.

Sparse is better than dense

This is referring back to the code sample above. A lot of times as programmers we might want to do a lot of functionality with just one line of code. However, spreading code over many lines is better than having one line do all the work.

Readability counts

This means your code should be easily readable, Instead of using single-letter variables or not indenting (however, Python forces this). Use what will be read and easily understood by yourself and other developers. Remember Code is read more often than it’s written

Special cases aren’t special enough to break the rules

Programming is full of best practices that programmers should strive for in their code. Skirting these practices for a quick hack may be tempting, but can lead to a rat’s nest of inconsistent, unreadable code.

Although practicality beats purity

There may be cases where you might want to make an exception to the rule above. Bending over backward to adhere to rules can result in highly-abstract, unreadable code. Walking the line between these two rules becomes easier with experience. And in time, you’ll not only learn the rules but also learn when to break them.

Errors should never pass silently

Never let errors that may occur, confuse the reader. You can easily resolve this by printing a string when an error occurs. Just because programmers often ignore error messages doesn’t mean the program should stop emitting them.

Unless explicitly silenced

Regarding the rule above. You can always choose to explicitly ignore the errors your programs cause, just be sure you are making the conscious choice to do so and be clear about it.

In the face of ambiguity, refuse the temptation to guess

If your code isn’t working, there is a reason, and only careful, critical thinking will solve it. Refuse the temptation to blindly try solutions until something seems to work; often you have merely masked the problem rather than solved it.

There should be one -- and preferably only one -- obvious way to do it

It turns out that having three or four different ways to write code that does the same thing is a double-edged sword: you have flexibility in how you write code, but now you have to learn every possible way it could have been written in order to read it. This flexibility isn’t worth the 3x or 4x effort needed to learn a programming language.

Although that way may not be obvious at first unless you’re Dutch

This line is a joke. Guido van Rossum, the creator of Python, is Dutch. Learning or recalling a rule in Python would be easier for him than it would be anybody else, on average.

Now is better than never

This simply tells us that we should not spend too much time planning and pre-optimizing; get something down that does the job and iterate on it. Don’t procrastinate and Don’t put off the inevitable

Although never is often better than right now

This is referring to the previous rule that we should put some thought into what we are doing so you don’t head off down a path that later has no graceful way back up.

If the implementation is hard to explain, it’s a bad idea

This is telling us that If the implementation is complicated, it is definitely not simple, meaning it is nowhere near a final draft, meaning it’s not good to put out as one.

If the implementation is easy to explain, it may be a good idea

These two rules remind us that if high-performance code is so complicated as to be impossible for programmers to understand and debug, then it’s bad code. But alas, just because it’s easy to explain a program’s code to someone else doesn’t mean it isn’t bad code. Programming is hard

Namespaces are one honking great idea — let’s do more of those!

Namespaces (and also global and local scopes) are key for preventing names in one module or scope from conflicting with names in another. But also remember that flat is better than nested: As great as they are, namespaces should be made only to prevent naming conflicts, and not to add needless categorization.

Like all opinions about programming, the ones written here can be argued against or may simply be irrelevant to your situation. Arguing over how code should be written is rarely as productive as you think it is. (Unless you’re writing an entire book full of programming opinions.)

Comments (2)

Precious Olusola's photo

Great!. There are 20 principles of the ZEN OF PYTHON. having 19 lines of text. (which you've explained),and a blank line. And my interpretation is that the blank line means "Make use of whitespace".

LordGhostX's photo

I love this insight