SKIP THE SHIPPING
Use code NOSHIP during checkout to save 40% on eligible eBooks, now through January 5. Shop now.
Register your product to gain access to bonus material or receive a coupon.
The real-world guide to enterprise-class Python development!
Python isn't just a tool for creating short Web scripts and simple prototypes: its advantages are equally compelling in large-scale development. In Python Programming Patterns, Thomas Christopher shows developers the best ways to write large programs with Python, introducing powerful design patterns that deliver unprecedented levels of robustness, scalability, and reuse. Christopher teaches both the Python programming language and how to "program in the large" with Python, using objects, modularization, toolkits, frameworks, and other powerful tools and techniques.
If you've ever thought it would be great to use Python in real enterprise development, you're about to learn howwith Python Programming Patterns!
Introduction.
Acknowledgments.
1. Getting Started.
Why Write Larger Programs in Python? Running Python. Numbers. Lists, Strings, and Tuples. Logical Values. Dictionaries. Assignments. Garbage Collection. Operators. Wrap-Up.
Python Statements. Example: Word Count. Wrap-Up. Exercises.
Importing Modules. Importing Names from Modules. Avoiding Namespace Pollution. Reloading Modules. Search Paths. Packages. Example Stack Module. Critique of Modules. Wrap-Up. Exercises.
Instances and Classes. Class Declarations. Instances. Methods. Single Inheritance. Visibility. Explicit Initializer Chaining. Example: Set Implementation. Critique. Example: BaseTimer. Inheritance As Classification. Multiple Inheritance. Recapitulation of the Scope of Names. Testing Objects and Classes. Wrap-Up. Exercises.
Concept of Design Patterns. Creational Patterns. Structural Patterns. Behavioral Patterns. Wrap-Up. Exercises.
Parameter and Argument Lists. Three-Level Scopes. Functional Programming. Function Objects. Built-In Functions. Wrap-Up. Exercises.
File Objects. Execution Environment. Other Useful Modules. Wrap-Up. Exercises.
Common Sequence Operations. Tuples. Lists. Wrap-Up. Exercises.
String Literals. Strings as Sequences. String Methods. Example: Splitter. String Formatting: The % Operator. Wrap-Up. Exercises.
Dictionary Operations. Example: Union-Find Algorithm. Persistence and Databases. Wrap-Up. Exercises.
Exception Classes. Minimal Exception Handling. Examining the Exception. Raising Exceptions. Tracebacks. Re-Raising Exceptions. Raise with Strings. Try-Except-Else. The Try-Finally Statement. Wrap-Up. Exercises.
Type Objects. Members and Methods. Numbers, Strings, Tuples, Lists, and Dictionaries. Modules. User-Defined Functions. Code Objects. Classes. Class Instances. User-Defined Methods. Built-In Functions and Methods. Slice. Xrange. File. Frame. Traceback. Example: Scopes. Wrap-Up. Exercises.
Python Interpreter Startup. Run-Time Compilation. Wrap-Up. Exercises.
Special Methods. Methods for All Objects. Operators. Arithmetic Operators. Augmented Assignment. Rich Comparisons. Attribute Access. Function Call Method. Wrap-Up. Exercises.
Special Methods for Container ADTs. DEQueue. Multidimensional Arrays. Class Versions of Built-In Data Types. Wrap-Up. Exercises.
Priority Queue Operations. Priority Queue Implementation. Unique Elements. Critique. Wrap-Up. Exercises.
Set Operations. Implementation. PureSet: A Protection Proxy. SetEnumeration. Wrap-Up. Exercises.
Threads. Race Conditions. Locks and Mutual Exclusion. Monitor Pattern. Producer-Consumer. Deadlock. Example: Future. Wrap-Up. Exercises.
Shared Database Operations. Example: Dining Philosophers. Implementation of SharedDB. Wrap-Up. Exercises.
Simple RunQueue. Implementing RunQueue. Detecting Termination of an Object on the RunQueue. TransactionQueue. Example of TransactionQueue: Dining Philosophers. Wrap-Up. Exercises.
Overall Behavior of re Module. re Syntax. Functions in re Module. Pattern Objects. Match Objects. Other Modes. Other Methods and Functions. Example: Scanner. Wrap-Up. Exercises.
Overview of the Process. Implementing a Calculator. Building a Tree. Wrap-Up. Exercises.
Contents. Software. Advice to the Reader.
The major purpose of this book is to teach the Python programming language and, in doing so, to concentrate on facilities that make it easier to write moderately large programs, say 5,000 lines or so. Programming in the large is more difficult than writing short scripts. Writing a 5,000-line program is not just 100 times as much work as writing a 50-line program. The way you write a 50-line script does not work for 5,000-line programs.
The secret for successfully writing larger programs is modularization, breaking them into understandable, manageable components. Your goal will not only be to make the software comprehensible, writable, debuggable, and maintainable, but to make it reusable. The best way to write a 5,000-line program is not to have to write all 5,000 lines right then. If somebody else has written code you need and it is available, use it. The library of modules available with Python is large and full of useful code.
When you do write code, it is best to make it reusable. There is no reason to implement the same kind of thing over again. This means you typically will need to over-design the code, to make it more general than you need the first time. The object-oriented design patterns, that we will look at in Chapter 5, are useful ways to think about the design. They are stylized ways of using things which make the design clean and help you remember how to use the objects.
When you are implementing your designs, of course, there are numerous patterns available to reuse: data structures, algorithms, mathematics, concurrent and object-oriented patterns. Where there are well known ways of doing things, it is not cost effective to be creative.
Design and Programming TechniquesWe will be looking at several kinds of software designs, components, and techniques. The fundamental way to organize software is the module. At a higher level, modules can be grouped into packages. Python's handling of modules and packages are the subject of Chapter 3.
Defining classes of objects is fundamental to many techniques. Objects and classes are the subject of Chapter 4 and object-oriented design techniques are the subject of Chapter 5.
Python has some built-in functions that are useful for functional programming. We discuss these in "Functional Programming" in Chapter 6.
Data types are not just sets of values. They include the operators, functions, and methods of manipulating those values. Abstract Data Types, ADTs, are data types implemented in software as opposed to the "concrete" data types built in to the language. Python has excellent facilities for implementing ADTs. You can define with "special methods" how your data type will respond to operators such as addition, x + y, or subscripting, xi. We devote Chapter 14 to looking at most the special methods. Chapter 15 is devoted to the subscripting and "slicing" special methods used to implement abstract container data types. Chapter 16 and Chapter 17 give examples of abstract container data types: priority queues and sets.
Concurrency involves allowing several threads of control (mini-programs) to run interleaved over the same period of time interacting with each other. They improve performance by allowing one part of the program to execute while another is waiting information to arrive. They also aid in program design, since it is often easier to design and understand the smaller programs than it is to design and understand a program that tries to do all their functions together. We discuss concurrency in Chapter 18, including the facilities available in Python's threading module, the monitor pattern (used to protect data from getting scrambled by concurrent access), and the dangers of deadlock and how to avoid it. Chapter 19 is devoted to an example monitor, Shareddb, that protects a shared data base from being mangled by concurrent updates and protects the transactions using it from deadlock. Chapter 20 presents another monitor, RunQueue, that allows thread objects to be reused. TransactionQueue is a variant of RunQueue to be used with SharedDB which automatically reschedules transactions that need to be tried again when they were unable to commit their changes to a data base.
Chapter 21 is devoted to regular expressions and Python's re module. Regular expressions are widely used to extract significant parts of text strings. The chapter includes an example scanner used by the parser presented in the next chapter. Chapter 22 shows how to use the TCLLk parser to recognize and execute simple statements. The behavior of the parser is specified by a context-free grammar augmented with "action symbols." Parsers are the next level up from regular expressions, facilitating the processing of text with nested subexpressions. The parser is an example of a framework: the parser is in control and you must write code that plugs into it.
SoftwareThis book comes with software available through the author's web site, toolsofcomputing.com. Some of the software is described in this book; some is not because it would not demonstrate any new principles. There are three varieties of software:
Abstract Data TypesThis book contains and describes the abstract container data types:
Also included is a prototype ADT implementation of rational numbers. Not discussed in the book, but available through the web site are multi-maps, directed graphs, undirected graphs, and bit sets.
Concurrent ProgrammingThis book contains implementations of objects to aid in writing concurrent programs:
Included with the software, but not described in the book, are the translation of classes from the Tools of Computing thread package in Java, described in our book High-Performance Java Platform Computing. This includes the SharedTableOfQueues data structure that resembles JavaSpaces and the Linda system.
Parsing FrameworkChapter 22 shows the use of a parser generator and parser, the TCLLk system. TCLLk is available at the web site. The parser generator takes context-free grammars and generates parsing tables for them, if possible. The tables can be translated for use in a number of programming languages including Python, Java, and Icon. All the ports are available, not just the Python.
Included with TCLLk is a class StringScanner that provides an alternative to regular expressions for extracting usable parts of strings.
What the Book Is NotBecause of the space that must be devoted to presenting the Python language, this book cannot be a hard-core object-oriented design patterns book. Chapter 5 describes most of the usual design patterns and they are demonstrated throughout the book in the implementations of software, but they are not the exclusive interest.