The Zen of Python is a collection of 19 observations noted by Tim Peters, one of the creators of Python. While the original collection had 20 aphorisms, Guido van Rossum dismisses the final one as a bizarre joke by Peters.
The collection was standardized in 2004 as PEP 20 since it significantly impacted the Python community’s programming process. Bearing these observations in mind when writing code is not mandatory, but it certainly helps ensure quality code.
Python includes the collection as an easter egg, and you can read the list of aphorisms by running “import this” on the interpreter.
We discuss the meanings of the aphorisms and how they can help you improve your code in this post.
The Zen of Python: A Breakdown
#1 Beautiful is Better Than Ugly
Programmers are problem-solving experts, but since writing, documenting, and maintaining Python code is typically a team effort, plainly crafting a solution to a problem is not enough. Ideally, the code needs to be readable and elegant.
But what makes code “beautiful”? Just like in life, beauty is subjective in Python programming. However, the rule of thumb is that the code must be easy to understand for any developer looking at it.
In other words, if a program works fine, it does not mean it’s beautiful and elegant. Removing unnecessary conditions and simplifying your solutions will make your code beautiful.
#2 Explicit is Better Than Implicit
Reading this observation, one could conclude that it’s self-explanatory. But many fail to implement it when they code.
The idea behind this aphorism is that writing verbose code is better than writing indirect code. Python programmers need to do everything they can to ensure that the functionality of their code doesn’t get hidden behind hard-to-understand language.
Put simply, you must write code that another programmer with no previous knowledge of the program should be able to understand how it’s working.
#3 Simple is Better Than Complex
Pulling out a pressure washer to clean the dishes after dinner might be one way to go about it, but it’ll likely damage the plates. Not to mention, it is a daft solution to the problem.
By the same token, writing complex code to solve a simple program is impractical. Python programmers must avoid overcomplicating their solutions, even if they may look smart and work.
Complicating your programs will ultimately do more damage, and your team will not appreciate it.
#4 Complex is Better Than Complicated
While doing the dishes with a pressure washer is impractical, using the pressure washer may be the right way to go if you’re cleaning a car.
The previous observation and this one remind programmers that there are both simple and complex solutions to the same problem. But just like you wouldn’t wash the dishes with a pressure washer, you wouldn’t wash a car with a small scrubber.
The meaning of this aphorism is that valuing simplicity over complexity may be the right way to go in most situations. Still, when simple solutions are impractical, you are better off implementing the complex solution.
In simple words, Python programmers should remember the limits of simplicity.
#5 Flat is Better Than Nested
It is common for programmers to have a knack for organizing things into categories and subcategories to separate their programs’ functionalities. Many programmers believe that this pays off since order is better than chaos.
However, organizing code in this way can create more confusion than organization. This isn’t to say that putting all of your code in one top-layer module is a bad idea. But when you add more subcategories into the mix, the code becomes more and more complicated.
Sticking to a flat structure is the best way to keep your programs simple.
#6 Sparse is Better Than Dense
Programmers often feel the need to emphasize their skills with over-elaborate code. There’s an entire culture behind doing complicated tasks in one line of code.
This is not to say that one-liners are bad. In some situations, writing solutions that way is justified. That said, this aphorism indicates that programmers should never compromise readability to fit all the functionality in one line of code.
#7 Readability Counts
When it comes to Python, readability should always be the top priority. Programmers are paid to write the code once, but many people will likely read the code several times.
Every Python developer needs to take this into account. Avoid dropping vowels from function and variable names to ensure the code remains clear through and through.
#8 Special Cases Aren’t Special Enough to Break the Rules
There is no shortage of best practices Python programmers need to follow. This aphorism indicates that it’s better to follow the norm than write code your own way since inconsistencies make the code unreadable and difficult to work with.
#9 Although Practicality Beats Purity
You can think of this as an extension of the previous observation. While it is always better to follow the best practices, putting in extra effort only so you can adhere to the rules can also make code unreadable.
If your method of solving a problem is easier to understand and more practical than the solution the best practices indicate, it is smarter to make an exception and deviate from the best practices.
#10 Errors Should Never Pass Silently
When a program returns None or an error code and does not raise an exception, the error is called a silent error.
The thinking behind this aphorism is that it’s better for a program to crash than to throw a silent error and continue running. This is because silencing errors can lead to complicated bugs down the road, and fixing those bugs will be much more challenging.
#11 Unless Explicitly Silenced
This is an extension of the previous lesson. In some situations, programmers may want to ignore the errors that a program throws. In these instances, it’s best practice to explicitly silence the errors.
#12 In the Face of Ambiguity, Refuse the Temptation to Guess
One of the first things programmers learn is that computers only do what users instruct them to do. In other words, if your program does not behave as you expect, it is performing your instructions as they are, and there’s a lapse in your solution.
Fixing the unwanted behavior by trying many different approaches until one works out is not the right strategy. It might cover up the problem and not solve it.
This aphorism states that you must refuse the temptation to blindly try different solutions. You will need to slowly walk through the code and think about the logic to create the necessary solution.
#13 There Should Be One - And Preferably Only One - Obvious Way to Do It
If you’re familiar with the Perl programming language, you may know its motto: “There’s more than one way to do it!”
But this motto ignores that having several options typically results in choice overload. This situation can also happen when a Python programmer finds several ways to write code that accomplishes the same goal.
Putting in the extra work to learn every solution to a problem is unnecessary. This aphorism asks programmers to narrow down the obvious solution and implement it.
#14 Although That Way May Not Be Obvious at First Unless You’re Dutch
This lesson reflects Tim Peters’ sense of humor since van Rossum, the creator of Python, is Dutch.
The lesson might seem light-hearted but underlines an important fact – a programmer may not be able to understand and recall the rules of a language unless they created the language.
Having a beginner’s mindset is key to improving your programming skills.
#15 Now is Better Than Never
It means that if a program is stuck in an infinite loop, crashes, or hangs, it is worse than a program that does not.
#16 Although Never is Often Better Than *Right* Now
This aphorism indicates that waiting for a program to finish executing is better than terminating the program early and basing your response on incorrect results.
#17 If the Implementation Is Hard to Explain, It’s A Bad Idea
Some programmers believe that the code is good enough if they can understand their code. However, as mentioned earlier, programming is a team activity.
If you cannot easily explain your solution to your teammates, it is likely that the solution is too complicated.
#18 If the Implementation Is Easy to Explain, It May Be a Good Idea
An extension to the previous lesson, this lesson says that if code is easy to explain, it doesn’t indicate that the code is good or bad.
#19 Namespaces Are One Honking Great Idea - Let’s Do More of Those!
In this final aphorism, there is a reference to namespaces, which are abstractions that organize the names assigned to objects.
All this lesson is saying is that the way Python organizes the symbolic names is amazing.