The Zen of Python: A guide to Python’s design principles | by Vishal Sharma | Towards Data Science

A Pythoneer once wrote 20 aphorisms stating how one can write beautiful and clean code with Python. Came to be known as “The Zen of Python”, these aphorisms exploded amongst Python developers. Tim Peters wrote these BDFL’s (Benevolent Dictator For Life, a nickname of Python creator Guido van Rossum) 20 guiding principles for Python’s design but the last aphorism was left for van Rossum to fill in.
Till today, there are 19 aphorisms as Rossum said that the last aphorism is “some bizarre Tim Peters in-joke.” But, what do these aphorisms mean?. Let’s crack it up!
The Zen of Python
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!
You can open “Easter Egg” in your Python IDE by typing:
import this
Beautiful is better than ugly
Being a developer, writing code and making it run is not the only job to do. Python is known for its readability and simplicity. So, why tamper it? Writing clean and readable code is an art which is appreciated by other programmers and let them understand every bit.
def collatz(num):    if num%2 == 0:        return num//2    else:        return 3 * num + 1number = input("Enter a number: ")while number != 1:    number = collatz(int(number))    print(number)
In the above code, there is no need to add “else”. It feels unnecessary at the point. Else, to make it better and clean, you can do something like:
def collatz(num):    if num%2 == 0:        return num//2        return 3 * num + 1
Explicit is better than implicit
The aphorism speaks for itself. It means that it is better to make the code more verbose and explicit. Doing this will make the code readable. Hiding code functionality might have repercussions as other programs might not be able to understand the code.
Simple is better than complex
Why build a complex code when you can build a simpler one.
def recursion_reverse(s):    if(len(s)==1):        return s    else:        return recursion_reverse(s[1:]) + s[0]original_string = "ABC"print("Reversed String : ", recursion_reverse(original_string))
You can do the in just two lines of code too.
my_string = “ABCD”reversed_string = my_string[::-1]
Complex is better than complicated
The above aphorism stated that simple is better than complex. And, now this one says “Complex is better than complicated”. It is getting confusing! A complex problem might require a complex technique to overcome it but it shouldn’t be complicated.
Complications in code make fellow programmers confused. Even if the program is complex, try keeping it on the simpler side which can be easily read and understand. Complicated code will suck effort and time! And, programmers can’t afford to lose time.
Flat is better than nested
Coders like to create sub-modules for each functionality. Let’s say, I build a module named “spam” and added submodule “foo” and in it, I added “baz”.
Now, accessing another subpackage from baz will be like:
from spam.foo.baz import eggs
Nesting and hierarchies do not add organization but bureaucracy!
Sparse is better than dense
Sometimes we tend to do everything in just one line of code. You might get the correct output. But, what about readability? Can someone understand it without peeking into it for a long time?
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))))
The same could have broken into parts and could have been written to get the same result. Spread out code is a delight and denser one infuriates co-workers.
Readability counts
Do you go to StackOverflow every time you are stuck with your code? So, what code do you take a look at? Readable one or complicated piece!
It is said that code is read more than written. So please, for the sake of readers starts writing code that it is readable as it is loved by our fellow programmers.
Special cases aren’t special enough to break the rules
A programmer must adhere to good “programming practices”. Let’s say, you import a library but it does not adhere to good programming practices. It must help you in getting your task done but keep in mind, libraries and languages should always follow the best “programming practices” and known for their consistency.
Although practicality beats purity
Contradictory to the above “Special cases aren’t special enough to break the rules” aphorism, this one suggests there might be an exception to the given set of rules. The keyword here is “might”.
Errors should never pass silently
When a function returns None, that is the time you are in the trap of silent errors. It is better to get errors but not silent errors. If you avoid such errors, it can lead to bugs, and further to crashes.
That’s why, using the “try-except” statement becomes important in the code. Wherever you think something fishy can go on, you must add this combo and get to know about these silent errors.
Unless explicitly silenced
Sometimes you want to ignore an error in the code, the best practice is to make the error explicitly silenced.
In the face of ambiguity, refuse the temptation to guess
Computers do what we want them to do. Still, these machines have made us superstitious. There is always a reason why a computer code is not behaving properly. Only and only your logic can fix it. So, break the temptation to guess and blindly try solutions until code works.
There should be one — and preferably only one — obvious way to do it
In Perl programming, there is a saying which says — “There’s more than one way to do it!” Using three-four codes to do the same thing is just like having double-edged sword. Not only it consumes time to write it but every fellow must be able to read your 3–4 methods without any issues. Flexibility in this practice isn’t worth celebrating.
Although that way may not be obvious at first unless you’re Dutch
Referring to Guido van Rossum, Python creator, this aphorism says that the language rule will not be easy to learn or recall unless and until you are the creator of the code. A joke referring to BDFL!
Now is better than never
This little aphorism says that code stuck in an infinite loop or in a never-ending loop is worse than having code that doesn’t.
Although never is often better than *right* now
It is better to wait for a program to end than to terminate it early and get incorrect results. This aphorism and the above one “Now is better than never” resemble each other and contradict each other at the same time.
If the implementation is hard to explain, it’s a bad idea
If you are explaining your code to someone and it is getting hard to explain it to your acquaintances or co-workers, then there is something wrong with your code. It is definitely not simple and is complicated!
If the implementation is easy to explain, it may be a good idea
Just opposite to above aphorism, this one simply says a simple, readable code is easy to explain. And, if you are able to do it, you are on the right track.
Namespaces are one honking great idea — let’s do more of those!
In Python, a namespace is basically a system to have a unique name for each and every object. It is a great way to access every underlying object.
a = 2print('id(a) =', id(a))a = a+1print('id(a) =', id(a))print('id(3) =', id(3))
It outputted:
id(a) = 9302208id(a) = 9302240id(3) = 9302240
The way Python organizes variables under the hood is just unbelievable. That’s why namespaces are cool!
Conclusion
Python is amazing! That’s why millions of developers use it, code in it, analyze data with it, and build models using it. The guidelines made for it only motivates programmers to write simple, readable, and clean code. Next time you sit for coding, try following these guidelines.
PEP 20 — The Zen of Python
PEP 20 — The Zen of Python