The Zen of Python

Writing a complex program is something like designing a building. The architect's constraints include time, money, good taste, and the structural limits of the materials. Programming also requires balancing multiple needs—often including time, money, the feature requests of multiple groups of people, and the availability of sufficient quantities of caffeine.

Pythonista Tim Peters contributed 19 guidelines for good Python code. We consider them the best distillation of the Python philosophy of programming. They're on this Web page:

http://www.python.org/doc/humor/#zen

These are design principles, not rules to be followed blindly. They're meant to encourage you to think. In some cases the principles may appear contradictory. That's a reflection of the fact that programming sometimes requires balancing conflicting requirements. It's like the old saying: "Good, fast, cheap—pick any two." The principles can help you decide how to prioritize these requirements.

The principles were originally written to guide the development of Python itself, but they also apply to writing your own programs. That's how we discuss them here.

Some of the most important guidelines are these:

Explicit is better than implicit. Good code is as self-explanatory as possible:

• Use names that explain the purpose of the objects they represent.

• Include comments in your code when it isn't obvious what a particular line or block does.

• Avoid hidden effects. (For example, printing to the screen shouldn't erase your hard drive.)

Readability counts. A good program is easy for a human to read and understand. If two blocks of code produce the same result, consider using the one that's easier to read. (Sometimes cryptic code runs faster, but speed isn't the primary goal of most Python programming.)

Errors should never pass silently. If you write code that doesn't alert the user of errors, the errors might cause the program to give incorrect results:

• Build explicit error checking into your code.

• Write code to catch any errors that you haven't thought of.

• Report errors to the user of your program.

There should be one—and preferably only one—obvious way to do it. This guideline ("There's only one way," for short) is the most popular among people in the Python community. This is partly in response to the motto of Perl programmers, which is, "There's More Than One Way To Do It." The Python community creates and popularizes standard coding idioms(preferred ways of performing certain tasks). Using standard idioms saves time because the code is already mostly written; you just plug in your data and variables. Python For Dummies includes many standard idioms to get you started.

Typing import this at the Python prompt in Python 2.1.2 or higher will print the entire list:

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 special enough to

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

Most computer programs have bugs. When you discover problems with the way your program works or the results it gives, you debug to

• Find the source of the mistake.

• Fix the lines of code causing the problem.

As you get comfortable with programming and Python, you get a better sense for how the computer "thinks," which helps you figure out bugs more quickly. You'll become familiar with common causes for common problems like:

• Syntax errors. Missing punctuation is the most common syntax mistake. For example, if you try to create a string but forget a quotation mark, you'll get an error like this:

• >>> mystring = "No! Not the Knights who say 'Ni'!

• mystring = "No! Not the Knights who say 'Ni'!

• SyntaxError: EOL while scanning single-quoted string

Tip You'll have fewer syntax errors in your programs if you use a Python- aware text editor that prints different syntax in different colors. Tips for avoiding common syntax errors can be found throughout Python for Dummies.

Misspelled names. If you name an object and then misspell the name when you refer to it later, you'll get an error. For example:

>>> print lumbrejack

Traceback (most recent call last):

File "<stdin>", line 1, in ? NameError: name 'lumbrejack' is not defined

Using the wrong types of values. For example, if you have a number in string format (perhaps from the raw_input() function, which converts the input into a string) and you try to do arithmetic with it, you'll get a result you didn't expect, like this:

>>> x = raw input("Enter a number: ") Enter a number: 45 >>> x * 2 '4545'

Creating infinite loops. If you create a loop by using a condition that never terminates, your program will try to run forever, like the brooms that the Sorcerer's Apprentice creates:

sorcerer = "asleep" def make broom():

print "another broom!" while sorcerer == "asleep": make broom()

Tip Chapter 10 shows you how to create loops that you can control.

Was this article helpful?

0 0

Post a comment