DEV Community

Cover image for The Zen of Python; An In-depth Explanation
LordGhostX
LordGhostX

Posted on • Updated on • Originally published at lordghostx.hashnode.dev

The Zen of Python; An In-depth Explanation

The Zen of Python by Tim Peters are guidelines for how you should write your Python code. 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!"""
Enter fullscreen mode Exit fullscreen mode

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 results from being so easy to use.

# code 1

file = "lyrics.txt"
open("disordered.txt", "w").write("\n".join(map(lambda x: x[::-1], open(file, "r").read().split("\n")[::-1])))
Enter fullscreen mode Exit fullscreen mode
# 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)
Enter fullscreen mode Exit fullscreen mode

Which of these codes do you prefer and feel is easy to understand?

Explicit is better than implicit

This means that you should avoid hiding your code functionality behind obscure language features that require familiarity to understand fully. 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 issue, 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 answer. But this is better than using a complicated one. Choose 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. Suppose you make packages and modules that require code like import spam.eggs.bacon.ham.foo.bar, then you’re making your code too complicated.

Sparse is better than dense

This refers back to the code sample above. 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 regulations 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 occurring errors that confuse the reader. You can quickly 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

You can always choose to ignore the errors your programs cause explicitly. 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 try solutions until something seems to work blindly; 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 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 for anybody else, on average.

Now is better than never

This 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 refers 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 tells us that If the implementation is complicated, it is 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 programmers can't understand and debug, it’s destructive code. But alas, just because it’s easy to explain a program’s code to someone else doesn’t mean it isn’t destructive code.

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

Namespaces (and global and local scopes) are vital 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 add needless categorization.

Top comments (3)

Collapse
 
chrisgreening profile image
Chris Greening

Great article! Python was the first programming language I learned and The Zen of Python has been a huge influence on both my coding style and my life in general. I find myself quoting it all the time even outside of programming lol

Collapse
 
lordghostx profile image
LordGhostX

Niceeeee 🤩🤩🤩

Collapse
 
hunterpp profile image
Hunter Peress

Would love examples for each ;-)