Home > Store

Python Programming Patterns

Register your product to gain access to bonus material or receive a coupon.

Python Programming Patterns


  • Sorry, this book is no longer in print.
Not for Sale


  • Copyright 2002
  • Dimensions: K
  • Pages: 560
  • Edition: 1st
  • Book
  • ISBN-10: 0-13-040956-1
  • ISBN-13: 978-0-13-040956-0

The real-world guide to enterprise-class Python development!

  • Enterprise development with Python!
  • 20+ object-oriented patterns for large-scale Python development
  • Maximizing scalability, robustness, and reuse
  • Leveraging modularization, toolkits, frameworks, metaprogramming, and more

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.

  • 20+ proven object-oriented patterns for large-scale Python development: creational, structural, and behavioral
  • Leverage the skills you've mastered in other object-oriented languages
  • Design Python systems for maximum reuse
  • Create cleaner, more comprehensible software systems
  • Make the most of persistence, concurrent programming, functional programming, and metaprogramming
  • Includes extensive working code and meaningful examples

If you've ever thought it would be great to use Python in real enterprise development, you're about to learn how—with Python Programming Patterns!

Sample Content

Online Sample Chapter

Objects and Classes in Python

Table of Contents



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.

2. Statements.

Python Statements. Example: Word Count. Wrap-Up. Exercises.

3. Modules and Packages.

Importing Modules. Importing Names from Modules. Avoiding Namespace Pollution. Reloading Modules. Search Paths. Packages. Example Stack Module. Critique of Modules. Wrap-Up. Exercises.

4. Objects and Classes.

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.

5. Object-Oriented Patterns.

Concept of Design Patterns. Creational Patterns. Structural Patterns. Behavioral Patterns. Wrap-Up. Exercises.

6. Functions.

Parameter and Argument Lists. Three-Level Scopes. Functional Programming. Function Objects. Built-In Functions. Wrap-Up. Exercises.

7. Input/Output.

File Objects. Execution Environment. Other Useful Modules. Wrap-Up. Exercises.

8. Sequences.

Common Sequence Operations. Tuples. Lists. Wrap-Up. Exercises.

9. Strings.

String Literals. Strings as Sequences. String Methods. Example: Splitter. String Formatting: The % Operator. Wrap-Up. Exercises.

10. Dictionaries.

Dictionary Operations. Example: Union-Find Algorithm. Persistence and Databases. Wrap-Up. Exercises.

11. Exceptions.

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.

12. Types.

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.

13. Programs and Run-Time Compilation.

Python Interpreter Startup. Run-Time Compilation. Wrap-Up. Exercises.

14. Abstract Data Types and Special Methods.

Special Methods. Methods for All Objects. Operators. Arithmetic Operators. Augmented Assignment. Rich Comparisons. Attribute Access. Function Call Method. Wrap-Up. Exercises.

15. Abstract Container Data Types.

Special Methods for Container ADTs. DEQueue. Multidimensional Arrays. Class Versions of Built-In Data Types. Wrap-Up. Exercises.

16. Priority Queues.

Priority Queue Operations. Priority Queue Implementation. Unique Elements. Critique. Wrap-Up. Exercises.

17. Sets.

Set Operations. Implementation. PureSet: A Protection Proxy. SetEnumeration. Wrap-Up. Exercises.

18. Concurrency.

Threads. Race Conditions. Locks and Mutual Exclusion. Monitor Pattern. Producer-Consumer. Deadlock. Example: Future. Wrap-Up. Exercises.

19. Transactions.

Shared Database Operations. Example: Dining Philosophers. Implementation of SharedDB. Wrap-Up. Exercises.

20. Run Queues.

Simple RunQueue. Implementing RunQueue. Detecting Termination of an Object on the RunQueue. TransactionQueue. Example of TransactionQueue: Dining Philosophers. Wrap-Up. Exercises.

21. Regular Expressions.

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.

22. Parser.

Overview of the Process. Implementing a Calculator. Building a Tree. Wrap-Up. Exercises.

23. Wrap-Up.

Contents. Software. Advice to the Reader.

Appendix A.




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 Techniques

We 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.


This 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 Types

This book contains and describes the abstract container data types:

  • DEQueue: a doubly ended queue,
  • prioque and prioqueunique: priority queues,
  • DisjointUnion: implementing the union-find algorithm,
  • Set and PureSet: a set.

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 Programming

This book contains implementations of objects to aid in writing concurrent programs:

  • Future: an assign-once variable,
  • Latch: a single element buffer,
  • SharedDB: a transaction-oriented monitor to share Python's dictionary-like data bases.
  • RunQueue: a queue to allow reuse of threads,
  • TransactionQueue: a version or RunQueue for transactions accessing a SharedDB object.

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 Framework

Chapter 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 Not

Because 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.


Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020