December 19, 2024

The Zen of Python

Zen of Python

The Zen of Python by Tim Peters, also know as PEP 20, is a collection of guiding principles designed into 20 aphorisms, only 19 of which were written. Guido van Rossum reportedly said that the missing 20th aphorism is “some bizarre Tim Peters in-joke” (Sweigart, 2018). Your Python code doesn’t have to follow this guidelines, but they’re good principles to keep in mind. The Zen of Python is an Easter Egg that appears if you run import this.

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

Analysis

1. Beautiful is better than ugly.

Words like “Beautiful” and “Ugly” are subjective terms. However, in Python, your code should strive to be readable, constant and visually elegant.

2. Explicit is better than implicit.

Explicit denotes being very clear and complete without vagueness, implication, or ambiguity. When something is said to be explicit, there is no question as to what is being expressed or conveyed—nothing is implied or assumed. Implicit, on the other hand, denotes that something is understood although not clearly or directly expressed or conveyed—there is implication, assumption, or question. Obviously, when writing Python code, your code should strive be explicitly clear.

3. Simple is better than complex

“Simple can be harder than complex: you have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains”

– Steve Jobs

In Python, your code should excel for its beauty and readability, without losing its simplicity! In other words, when developing Python code, don’t look for the most complex path! Try to keep it simple! Finding a simple solution to a simple problem should always be your goal, even if it is not that simple to do!

4. Complex is better than complicated

When the simple alternative is not possible, avoid the complicated solution! However, sometimes a complex problem requires a complex solution.…But always remember, a complex solution is better than a more complex one!

5. Flat is better than nested.

Avoid creating structures inside structures that are inside another structure. Sweigart (2018) jokingly points out a common trait among programmers is the predilection to organize things into categories, especially categories that contain subcategories which contain other sub-subcategories. This statement is very True. However, excessively nesting constructs like conditional statements, functions, classes or modules one inside the other is frowned upon and should be avoided.

6. Sparse is better than dense


In other words: don’t try to “cram” too much code into one line. Programmers have a tendency to try and cram as much functionality into as little code as possible as evident with the following one-liner code:

print('\n'.join("%i bytes = %i bits which has %i possible values." % (j, j*8, 256**j-1) for j in (1 << i for i in range(8))))

Although this impressive code resembles solutions you might see on CodeWars or HackerRank, this code will irritate your coworkers who will have to try to decipher it. Remember the first topic: “beautiful is better than ugly”!

7. Readability counts

The motto of Python is clarity. The language attempts to be as readable as the English language.

I’d like to mention one readability rule specifically: punctuation characters should be used conservatively, in line with their common use in written English or high-school algebra.

– Guido van Rossum

It is recommend not to drop vowels from variable names or write overly terse code. Code is read more often than it’s written, so explicit, readable code is more important than terse, undocumented code (Sweigart, 2018).

8. Special cases aren’t special enough to break the rules.

In General, programmers should always strive to adhere to best practices when coding. Sometimes it’s tempting to cut corners for a quick hack but this can lead to a rat’s nest of inconsistent, unreadable code.

9. Although practicality beats purity

However, Sweigart (2018), points out, “bending over backwards to adhere to rules can result in highly-abstract, unreadable code.” It is important to remember, no case is special enough that it bypasses the rules! Even if practicality supersedes purity!

10. Errors should never pass silently.

It is better for a program to crash than to let Errors pass silently. The bugs that will inevitably generate will be more difficult to catch in the future if errors are suppressed. Never “silence” an exception unless it is explicitly stated and silenced. Muting an exception is a serious code maintenance error as it can hide an error, sometimes harmless, sometimes critical! So pay attention! Do not do it

11. Unless explicitly silenced.

Although you can choose to explicitly ignore the errors caused by your program, just remember there are consequences for doing so.

12. In the face of ambiguity, refuse the temptation to guess.

Again, this has to do with making your code specific, clean, beautiful and related to the next Zen.

When your code does not work, never be tempted to blindly try various solutions until something seems to work. Often this leads to merely masking the problem rather than solving it (Sweigart, 2018). More often than not, critical thinking and analysis of the problem will lend itself to a solution.

13. There should be one—and preferably only one—obvious way to do it.

According to Sweigart (2018), This is a crack against the Perl programming language’s motto, “There’s more than one way to do it!” in Python it is preached that there should be only one way to reach a solution to the problem. That’s one of the reasons Python makes it so simple. Unfortunately, this aphorism did not prevent Python from incorporating three different ways of formatting strings. Sometimes, having multiple ways to code a solution can be a double-edge sword. Whenever possible, always strive for the optimal solution.

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

This joking reference to Python’s creator, Guido van Rossum who is Dutch. The joke being, Since Guido created Python, it’s reasonable to expect he would learn a rule or see an inconspicuous solution in Python faster than any one else in general.

15. Now is better than never.

Don’t spend too much time procrastinating or planning too much and doing too little! Sometimes it’s better to make a first version and iterate over it until it looks nice, pythonically speaking. Obviously, code that executes quickly is more better than code that executes slowly. Spend some time planning and pre-optimizing to find the best solution, but not too much!

16. Although never is often better than *right* now.

This aphorism seems to be in opposition of the previous one. However, sometimes it’s better to have no solution than to have a solution at all. Especially in the case when that solution can cause more harm than good to your program.

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

Again, simplicity is preached. Programs need to be understandable not just by the programmer who wrote it, but also by other programmers who maintain the code. If implementing Python code is so complicated that other programmers cannot understand than it is probably a bad idea and should be avoided. If you can’t say it, don’t do it

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

If implementing Python code seems logical, intuitive and easily explainable than it may be a good idea. Sweigart (2018) reminds us, that  just because code is easy to explain doesn’t mean it isn’t bad code.

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

A namespace is a collection of names and the objects that they reference. There are four distinct types of namespace that Python generates:

locals > nonlocals > globals > builtins

Namespaces (and also global and local scopes) are key for preventing names in one module or scope from conflicting with names in another. According to Sweigart (2019), as great as they are, namespaces should be made only to prevent naming conflicts, and not to add needless categorization. Since “Zen of Python” has been published, no new namespace has been introduced in Python. 

Conclusion

As you can see, the Zen of Python is just a collection of guiding principles and not necessarily rules set in stone. As you code, you should keep these principles in the back of your mind, but don’t allow them to impeded or interfere with your your own coding goals. Remember, rules are meant to be broken. So long as you know why you are breaking them – you should be fine! What are your thoughts on the Zen of Python? If you have different ideas? If so, please feel free to share them in the comments below.


References

BBC News. (2011). In quotes: Apple’s Steve Jobs. BBC News.
Retrieved from: https://www.bbc.com/news/world-us-canada-15195448

Hammond, J. (2017). A Brief Analysis of “The Zen of Python.”
Retrieved from: https://medium.com/@Pythonidaer/a-brief-analysis-of-the-zen-of-python-2bfd3b76edbf

Jones, R. (2011). Zen of Python – Guido’s Original Design Philosophy.
Retrieved from: https://pydanny-event-notes.readthedocs.io/en/latest/PyconAU2011/zen_of_python.html

Sweigart, A. (2018). The Zen of Python Explained. Invent with Python Blog.
Retrieved from: https://inventwithpython.com/blog/2018/08/17/the-zen-of-python-explained/

Leave a Reply

Your email address will not be published.