Contents

5.1. The Zen of Python

The Zen of Python by Tim Peters is a set of 20 guidelines for the design of the Python language and for Python programs. Your Python code doesn’t nec- essarily have to follow these guidelines, but they’re good to keep in mind. The Zen of Python is also an Easter egg, or hidden joke, that appears when you run import this :

import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. --snip--

5.1.1. NOTE

Mysteriously, only 19 of the guidelines are written down. Guido van Rossum, creator of Python, reportedly said that the missing 20th aphorism is “some bizarre Tim Peters in-joke.” Tim left it blank for Guido to fill, which he seems to never have gotten around to doing.

In the end, these guidelines are opinions that programmers can argue for or against. Like all good sets of moral codes, they contradict themselves to provide the most flexibility. Here’s my interpretation of these aphorisms:

Beautiful is better than ugly. Beautiful code can be thought of as easy to read and understand. Programmers often write code quickly without concern for readability. The computer will run unreadable code, but unreadable code is difficult for human programmers to maintain and debug. Beauty is subjective, but code that is written without regard for how understandable it is often ugly to others. The reason for Python’s popularity is that its syntax isn’t cluttered with cryptic punctuation marks like other languages, making it easy to work with.

Explicit is better than implicit. If I’d written only “This is self-explanatory,” I would have provided a terrible explanation for this aphorism. Similarly, in code, it’s best to be verbose and explicit. You should avoid hiding code’s functionality behind obscure language fea- tures that require deep language familiarity to fully understand.

Simple is better than complex. Complex is better than complicated.
These two aphorisms remind us that we can build anything with simple or complex techniques. If you have a simple problem that requires a shovel, it’s overkill to use a 50-ton hydraulic bulldozer. But for an enor- mous job, the complexity of operating a single bulldozer is preferable to the complications of coordinating a team of 100 shovelers. Prefer simplicity to complexity, but know the limits of simplicity.

Flat is better than nested. Programmers love to organize their code into categories, especially categories that contain subcategories that contain other sub-subcategories. These hierarchies often don’t add organization so much as they add bureaucracy. It’s okay to write code in just one top-level module or data structure. If your code looks like spam.eggs.bacon.ham() or spam[‘eggs’][‘bacon’][‘ham’] , you’re making your code too complicated.

Sparse is better than dense. Programmers often like to cram as much functionality into as little code as possible, as in the following line: print(‘:raw-latex:`\n`’.join(“%i bytes = %i bits which has %i possiblevalues.” % (j, j*8, 256** j-1) for j in (1 << i for i in range(8)))) . Although code like this might impress their friends, it’ll infuriate their co-workers who have to try to understand it. Don’t make your code try to do too much at once. Code that is spread out over multiple lines is often easier to read than dense one-liners. This aphorism is roughly the same as sim- ple is better than complex.

Readability counts. Although strcmp() might obviously mean the “string compare” function to someone who has been programming in C since the 1970s, modern computers have enough memory to write out the full function name. Don’t drop letters from your names or write overly terse code. Take the time to come up with descriptive, specific names for your variables and functions. A blank line in between sections of your code can serve the same function as paragraph breaks in a book, letting the reader know which parts are meant to be read together. This aphorism is roughly the same as beautiful is better than ugly.

Special cases aren’t special enough to break the rules. Although practicality beats purity. These two aphorisms contradict each other. Programming is full of “best practices” that programmers should strive for in their code. Skirting these practices for a quick hack might be tempting but can lead to a rat’s nest of inconsistent, unreadable code. On the other hand, bending over backward to adhere to rules can result in highly abstract, unreadable code. For example, the Java programming language’s attempt to fit all code to its object-oriented paradigm often results in lots of boilerplate code for even the smallest program. Walking the line between these two aphorisms becomes easier with experience. In time, you’ll learn not only the rules but also when to break them.

Errors should never pass silently. Unless explicitly silenced. Just because programmers often ignore error messages doesn’t mean the program should stop emitting them. Silent errors can happen when functions return error codes or None instead of raising exceptions. These two aphorisms tell us that it’s better for a program to fail fast and crash than to silence the error and continue running. The bugs that inevitably happen later on will be harder to debug because they’re detected long after the original cause. Although you can always decide to explicitly ignore the errors your programs cause, be sure you’re mak- ing the conscious choice to do so.

In the face of ambiguity, refuse the temptation to guess. Computers have made humans superstitious: to exorcise the demons in our com- puters, we perform the sacred ritual of turning them off and then on. Supposedly this will fix any mysterious problem. But computers are not magic. If your code isn’t working, there’s a reason why, and only careful, critical thinking will solve the problem. Refuse the temptation to blindly try solutions until something seems to work; often, you’ve merely masked the problem rather than solved it.

There should be one—and preferably only one—obvious way to do it. This is a broadside against the Perl programming language’s motto, “There’s more than one way to do it!” It turns out that having three or four different ways to write code that does the same task 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 to read other people’s code. This flexibility isn’t worth the increased 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.

Now is better than never. Although never is often better than right now. These two aphorisms tell us that code that runs slowly is obvi- ously worse than code that runs quickly. But it’s better to have to wait for your program to finish than to finish it too early with incorrect results.

If the implementation is hard to explain, it’s a bad idea. If the imple- mentation is easy to explain, it may be a good idea. Many things get more complicated over time: tax laws, romantic relationships, Python programming books. Software is no different. These two aphorisms remind us that if code is so complicated as to be impossible for pro- grammers to understand and debug, it’s bad code. But just because it’s easy to explain a program’s code to someone else doesn’t mean it isn’t bad code. Unfortunately, figuring out how to make code as simple as possible, and not any simpler, is hard.

Namespaces are one honking great idea—let’s do more of those! Namespaces are separate containers for identifiers to prevent naming conflicts. For example, the open() built-in function and the w ­ ebbrowser .open() function have the same name but refer to different functions. Importing webbrowser doesn’t overwrite the built-in open() function because both open() functions exist in different namespaces: the built- in namespace and the webbrowser module’s namespace, respectively. But keep in mind that flat is better than nested: as great as namespaces are, you should make them only to prevent naming conflicts, not to add needless categorization.

As with all opinions about programming, you can argue against those I’ve listed here, or they might simply be irrelevant to your situation. Arguing over how you should write code or what counts as “pythonic” is rarely as productive as you think it is. (Unless you’re writing an entire book full of programming opinions.)