Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 22, 2020 04:31 am GMT

The Zen of Python; An In-depth Explanation

The Zen of Python by Tim Peters are guidelines for how your Python code should be written. Your code doesnt have to follow these guidelines, but it's good to keep them in mind.

>>> import this"""The Zen of Python, by Tim PetersBeautiful 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 Pythons popularity is a result of being so easy to work with.

# code 1file = "lyrics.txt"open("disordered.txt", "w").write("
".join(map(lambda x: x[::-1], open(file, "r").read().split("
")[::-1])))
Enter fullscreen mode Exit fullscreen mode
# code 2file = "lyrics.txt"# first read the input filelyrics = open(file, "r").read()# split the lyrics into lines and reorder it in reverse formlyrics = lyrics.split("
")[::-1]# reverse each line in the lyricsreverse = lambda x: x[::-1]lyrics = list(map(reverse, lyrics))# merge the new lyrics togetherlyrics = "
".join(lyrics)# save the fileopen("disordered.txt", "w").write(lyrics)
Enter fullscreen mode Exit fullscreen mode

which of these codes do you prefer and feel is easy to work with?

Explicit is better than implicit

This means that you should avoid hiding your code functionality behind obscure language features that require familiarity to fully understand. 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 problem, 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 solution. But this is better than using a complicated one. Prefer 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. Its okay to have code in just one top-layer module or class instead of splitting up across multiple submodules or subclasses. If you make packages and modules that require code like import spam.eggs.bacon.ham.foo.bar, then youre making your code too complicated.

Sparse is better than dense

This is referring back to the code sample above. A lot of times 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 its written

Special cases arent 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 rats 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 rules can result in highly-abstract, unreadable code. Walking the line between these two rules becomes easier with experience. And in time, youll not only learn the rules but also learn when to break them.

Errors should never pass silently

Never let errors that may occur, confuse the reader. You can easily resolve this by printing a string when an error occurs. Just because programmers often ignore error messages doesnt mean the program should stop emitting them.

Unless explicitly silenced

Regarding the rule above. You can always choose to explicitly ignore the errors your programs cause, 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 isnt working, there is a reason, and only careful, critical thinking will solve it. Refuse the temptation to blindly try solutions until something seems to work; 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 in order to read it. This flexibility isnt worth the 3x or 4x effort needed to learn a programming language.

Although that way may not be obvious at first unless youre 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 anybody else, on average.

Now is better than never

This simply 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. Dont procrastinate and Dont put off the inevitable

Although never is often better than right now

This is referring to the previous rule that we should put some thought into what we are doing so you dont head off down a path that later has no graceful way back up.

If the implementation is hard to explain, its a bad idea

This is telling us that If the implementation is complicated, it is definitely not simple, meaning it is nowhere near a final draft, meaning its 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 to be impossible for programmers to understand and debug, then its bad code. But alas, just because its easy to explain a programs code to someone else doesnt mean it isnt bad code. Programming is hard

Namespaces are one honking great idea lets do more of those!

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

Like all opinions about programming, the ones written here can be argued against or may simply be irrelevant to your situation. Arguing over how code should be written is rarely as productive as you think it is. (Unless youre writing an entire book full of programming opinions.)


Original Link: https://dev.to/lordghostx/the-zen-of-python-an-in-depth-explanation-45fm

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To