The Zen Of Python – 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!
You need this book because you need to learn Python. Here are a few reasons why you might need to learn Python
Python reflects a number of growing trends in software development, putting it at or near the leading edge of good programming languages. It is a very simple language surrounded by a vast library of add-on modules. It is an open source project, supported by many individuals. It is an object-oriented language, binding data and processing into class definitions. It is a platform-independent, scripted language, with complete access to operating system API‘s. It supports integration of complex solutions from pre-built components. It is a dynamic language, which avoids many of the complexities and overheads of compiled languages.
This book is a close-to-complete presentation of the Python language. It is oriented toward learning, which involves accumulating many closely intertwined concepts. In our experience teaching, coaching and doing programming, there is an upper limit on the “clue absorption rate”. In order to keep within this limit, we’ve found that it helps to present a language as ever-expanding layers. We’ll lead you from a very tiny, easy to understand subset of statements to the entire Python language and all of the built-in data structures. We’ve also found that doing a number of exercises helps internalize each language concept.
Three Faces of a Language. There are three facets to a programming language: how you write it, what it means, and the additional practical considerations that make a program useful. While many books cover the syntax and semantics of Python, in this book we’ll also cover the pragmatic considerations. Our core objective is to build enough language skills that good object-oriented design will be an easy next step.
The syntax of a language is covered in the language reference manual available online. In the case of relatively simple languages, like Python, the syntax is simple. We’ll provide additional examples of language syntax.
The semantics of the language can be a bit more slippery than the syntax. Some languages involve obscure or unique concepts that make it difficult to see what a statement really means. In the case of languages like Python, which have extensive additional libraries, the burden is doubled. First, one has to learn the language, then one has to learn the libraries. The number of open source packages made available by the Python community can increase the effort required to understand an entire architecture. The reward, however, is high-quality software based on high-quality components, with a minimum of development and integration effort.
Many languages offer a number of tools that can accomplish the same basic task. Python is no exception. It is often difficult to know which of many alternatives performs better or is easier to adapt. We’ll try to focus on showing the most helpful approach, emphasizing techniques that apply for larger development efforts. We’ll try to avoid “quick and dirty” solutions that are only appropriate when learning the language.
Professional programmers who need to learn Python are our primary audience. We provide specific help for you in a number of ways.
Instructors are a secondary audience. If you are looking for classroom projects that are engaging, comprehensible, and focus on perfecting language skills, this book can help. Each chapter in this book contains exercises that help students master the concepts presented in the chapter.
This book assumes an basic level of skill with any of the commonly-available computer systems. The following skills will be required.
When you’ve finished with this book you should be able to do the following.
This book falls into five distinct parts. To manage the clue absorption rate, the first three parts are organized in a way that builds up the language in layers from central concepts to more advanced features. Each layer introduces a few new concepts, and is presented in some depth. Programming exercises are provided to encourage further exploration of each layer. The last two parts cover the extension modules and provide specifications for some complex exercises that will help solidify programming skills.
Some of the chapters include digressions on more advanced topics. These can be skipped, as they cover topics related to programming in general, or notes about the implementation of the Python language. These are reference material to help advanced students build skills above and beyond the basic language.
The first part, Language Basics introduces the basic feartures of the Python language, covering most of the statements but sticking with basic numeric data types.
Background and History provides some history and background on Python. Getting Started covers installation of Python, using the interpreter interactively and creating simple program files.
Simple Numeric Expressions and Output covers the basic expressions and core numeric types. Variables, Assignment and Input introduces variables, assignment and some simple input constructs. Truth, Comparison and Conditional Processing adds truth and conditions to the language. Loops and Iterative Processing.
In Functions we’ll add basic function definition and function call constructs; Additional Notes On Functions introduces some advanced function call features.
The second part, Data Structures adds a number of data structures to enhance the expressive power of the language.
In this part we will use a number of different kinds of objects, prior to designing our own objects. Sequences: Strings, Tuples and Lists extends the data types to include various kinds of sequences. These include Strings , Tuples and Lists. Mappings and Dictionaries describes mappings and dictionaries. Exceptions covers exception objects, and exception creation and handling.
Files covers files and several closely related operating system (OS) services. Functional Programming with Collections describes more advanced sequence techniques, including multi-dimensional matrix processing. This part attempts to describe a reasonably complete set of built-in data types.
The third part, Data + Processing = Objects, unifies data and processing to define the object-oriented programming features of Python.
Classes introduces basics of class definitions and introduces simple inheritance. Advanced Class Definition adds some features to basic class definitions. Some Design Patterns extend this discussion further to include several common design patterns that use polymorphism. Creating or Extending Data Types describes the mechanism for adding types to Python that behave like the built-in types.
Part four, Components, Modules and Packages, describes modules, which provide a higher-level grouping of class and function definitions. It also summarizes selected extension modules provided with the Python environment.
Modules provides basic semantics and syntax for creating modules. We cover the organization of packages of modules in Packages. An overview of the Python library is the subject of The Python Library. Complex Strings: the re Module covers string pattern matching and processing with the re module. Dates and Times: the time and datetime Modules covers the time and datetime module. Programs: Standing Alone covers the creation of main programs. We touch just the tip of the client-server iceberg in Architecture: Clients, Servers, the Internet and the World Wide Web.
Some of the commonly-used modules are covered during earlier chapters. In particular the math and random modules are covered in The math Module and the string module is covered in Strings. Files touches on fileinput, os, os.path, glob, and fnmatch.
Finally, part five, Projects, presents several larger and more complex programming problems. These are ranked from relatively simple to quite complex.
Areas of the Flag covers computing the area of the symbols on the American flag. Bowling Scores covers scoring in a game of bowling. Musical Pitches has several algorithms for the exact frequencies of musical pitches. What Can be Computed? has several exercises related to computability and the basics of finite state machines. Mah Jongg Hands describes algorithms for evaluating hands in the game of Maj Jongg. Chess Game Notation deals with interpreting the log from a game of chess.
This book can’t cover everything Python. There are a number of things which we will not cover in depth, and some things which we can’t even touch on lightly. This list will provide you directions for further study.
We have to adopt a style for presenting Python. We won’t present a complete set of coding standards, instead we’ll present examples. This section has some justification of the style we use for the examples in this book.
Just to continune this rant, we find that actual examples speak louder than any of the gratuitously detailed coding standards which are so popular in IT shops. We find that many IT organizations waste considerable time trying to write descriptions of a preferred style. A good example, however, trumps any description. As consultants, we are often asked to provide standards to an inexperienced team of programmers. The programmers only look at the examples (often cutting and pasting them). Why spend money on empty verbiage that is peripheral to the useful example?
One important note: we specifically reject using complex prefixes for variable names. Prefixes are little more than “visual clutter”. In many places, for example, an integer parameter with the amount of a bet might be called pi_amount where the prefix indicates the scope (p for a parameter) and type (i for an integer). We reject the pi_ as potentially misleading and therefore uninformative.
This style of name is only appropriate for primitive types, and doesn’t address complex data structures well at all. How does one name a parameter that is a list of dictionaries of class instances? pldc_?
In some cases, prefixes are used to denote the scope of an instance variables. Variable names might include a cryptic one-letter prefix like f to denote an instance variable; sometimes programmers will use my or the as an English-like prefix. We prefer to reduce clutter. In Python, instance variables are always qualified by self., making the scope crystal clear.
All of the code samples were tested on Python 2.6 for MacOS, using an iMac running MacOS 10.5. Additional testing of all code was done with Windows 2000 on a Dell Latitude laptop as well as a VMWare implementation of Fedora 11.
Here is a typical Code sample.
Typical Python Example
combo = { }
for i in range(1,7):
for j in range(1,7):
roll= i+j
combo.setdefault( roll, 0 )
combo[roll] += 1
for n in range(2,13):
print "%d %.2f%%" % ( n, combo[n]/36.0 )
The output from the above program will be shown as follows:
2 0.03%
3 0.06%
4 0.08%
5 0.11%
6 0.14%
7 0.17%
8 0.14%
9 0.11%
10 0.08%
11 0.06%
12 0.03%
Tool completed successfully
We will use the following type styles for references to a specific Class, method(), attribute, which includes both class variables or instance variables.
Tip
tip
There will be design tips, and warnings, in the material for each exercise. These reflect considerations and lessons learned that aren’t typically clear to starting OO designers.
I’d like to thank Carl Frederick for asking me if I was using Python to develop complex applications. At the time, I said I’d have to look into it. This is the result of that investigation.
I am indebted to Thomas Pautler, Jim Bullock, Michaël Van Dorpe, Matthew Curry, Igor Sakovich, Drew, John Larsen, Robert Lucente, Lex Hider, John Nowlan and Tom Elliott for supplying much-needed corrections to errors in previous editions.
John Hayes provided particular complete and meticulous copy-editing.