Developer’s Library: Essential References for Programming Professionals

Developer’s Library books are designed to provide practicing programmers with unique, high-quality references and tutorials on the programming languages and technologies they use in their daily work.

All books in the Developer’s Library are written by expert technology practitioners who are especially skilled at organizing and presenting information in a way that’s useful for other programmers.

Key titles include some of the best, most widely acclaimed books within their topic areas:

PHP and MySQL Web Development
Luke Welling & Laura Thomson
ISBN 978-0-672-32916-6

MySQL
Paul DuBois
ISBN-13: 978-0-672-32938-8

Linux Kernel Development
Robert Love
ISBN-13: 978-0-672-32946-3

Python Essential Reference
David Beazley
ISBN-13: 978-0-672-32862-6

Programming in Objective-C
Stephen G. Kochan
ISBN-13: 978-0-321-56615-7

PostgreSQL
Korry Douglas
ISBN-13: 978-0-672-33015-5

Developer’s Library books are available at most retail and online bookstores, as well as by subscription from Safari Books Online at safari.informit.com

Developer’s Library
informit.com/devlibrary

Python

Essential Reference

Fourth Edition

David M. Beazley

image

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City

Python Essential Reference

Fourth Edition

Copyright © 2009 by Pearson Education, Inc.

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

ISBN-13: 978-0-672-32978-4
ISBN-10: 0-672-32978-6

Printed in the United States of America

First Printing June 2009

Acquisitions Editor
Mark Taber

Development Editor
Michael Thurston

Managing Editor
Patrick Kanouse

Project Editor
Seth Kerney

Copy Editor
Lisa Thibault

Indexer
David Beazley

Proofreader
Megan Wade

Technical Editors
Noah Gift
Kurt Grandis

Publishing Coordinator
Vanessa Evans

Book Designer
Gary Adair

Compositor
Bronkella Publishing

Library of Congress Cataloging-in-Publication data is on file.

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Addison-Wesley cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

Bulk Sales

Addison-Wesley offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact

       U.S. Corporate and Government Sales
       1-800-382-3419
       [email protected]

For sales outside of the U.S., please contact

       International Sales
       [email protected]

To register this product and gain access to bonus content, go to www.informit.com/register to sign in and enter the ISBN. After you register the product, a link to the additional content will be listed on your Account page, under Registered Products.

For Paula, Thomas., and his brother on the way.

Contents at a Glance

Introduction

Part I: The Python Language

     1  A Tutorial Introduction

     2  Lexical Conventions and Syntax

     3  Types and Objects

     4  Operators and Expressions

     5  Program Structure and Control Flow

     6  Functions and Functional Programming

     7  Classes and Object-Oriented Programming

     8  Modules, Packages, and Distribution

     9  Input and Output

   10  Execution Environment

   11  Testing, Debugging, Profiling, and Tuning

Part II: The Python Library

   12  Built-In Functions

   13  Python Runtime Services

   14  Mathematics

   15  Data Structures, Algorithms, and Code Simplification

   16  String and Text Handling

   17  Python Database Access

   18  File and Directory Handling

   19  Operating System Services

   20  Threads and Concurrency

   21  Network Programming and Sockets

   22  Internet Application Programming

   23  Web Programming

   24  Internet Data Handling and Encoding

   25  Miscellaneous Library Modules

Part III: Extending and Embedding

   26  Extending and Embedding Python

Appendix: Python 3

Index

Table of Contents

Introduction

I: The Python Language

   1  A Tutorial Introduction

Running Python

Variables and Arithmetic Expressions

Conditionals

File Input and Output

Strings

Lists

Tuples

Sets

Dictionaries

Iteration and Looping

Functions

Generators

Coroutines

Objects and Classes

Exceptions

Modules

Getting Help

   2  Lexical Conventions and Syntax

Line Structure and Indentation

Identifiers and Reserved Words

Numeric Literals

String Literals

Containers

Operators, Delimiters, and Special Symbols

Documentation Strings

Decorators

Source Code Encoding

   3  Types and Objects

Terminology

Object Identity and Type

Reference Counting and Garbage Collection

References and Copies

First-Class Objects

Built-in Types for Representing Data

The None Type

Numeric Types

Sequence Types

Mapping Types

Set Types

Built-in Types for Representing Program Structure

Callable Types

Classes, Types, and Instances

Modules

Built-in Types for Interpreter Internals

Code Objects

Frame Objects

Traceback Objects

Generator Objects

Slice Objects

Ellipsis Object

Object Behavior and Special Methods

Object Creation and Destruction

Object String Representation

Object Comparison and Ordering

Type Checking

Attribute Access

Attribute Wrapping and Descriptors

Sequence and Mapping Methods

Iteration

Mathematical Operations

Callable Interface

Context Management Protocol

Object Inspection and dir()

   4  Operators and Expressions

Operations on Numbers

Operations on Sequences

String Formatting

Advanced String Formatting

Operations on Dictionaries

Operations on Sets

Augmented Assignment

The Attribute (.) Operator

The Function Call () Operator

Conversion Functions

Boolean Expressions and Truth Values

Object Equality and Identity

Order of Evaluation

Conditional Expressions

   5  Program Structure and Control Flow

Program Structure and Execution

Conditional Execution

Loops and Iteration

Exceptions

Built-in Exceptions

Defining New Exceptions

Context Managers and the with Statement

Assertions and _ _debug_ _

   6  Functions and Functional Programming

Functions

Parameter Passing and Return Values

Scoping Rules

Functions as Objects and Closures

Decorators

Generators and yield

Coroutines and yield Expressions

Using Generators and Coroutines

List Comprehensions

Generator Expressions

Declarative Programming

The lambda Operator

Recursion

Documentation Strings

Function Attributes

eval(), exec(), and compile()

   7  Classes and Object-Oriented Programming

The class Statement

Class Instances

Scoping Rules

Inheritance

Polymorphism Dynamic Binding and Duck Typing

Static Methods and Class Methods

Properties

Descriptors

Data Encapsulation and Private Attributes

Object Memory Management

Object Representation and Attribute Binding

_ _slots_ _

Operator Overloading

Types and Class Membership Tests

Abstract Base Classes

Metaclasses

Class Decorators

   8  Modules, Packages, and Distribution

Modules and the import Statement

Importing Selected Symbols from a Module

Execution as the Main Program

The Module Search Path

Module Loading and Compilation

Module Reloading and Unloading

Packages

Distributing Python Programs and Libraries

Installing Third-Party Libraries

   9  Input and Output

Reading Command-Line Options

Environment Variables

Files and File Objects

Standard Input, Output, and Error

The print Statement

The print() Function

Variable Interpolation in Text Output

Generating Output

Unicode String Handling

Unicode I/O

Unicode Data Encodings

Unicode Character Properties

Object Persistence and the pickle Module

10   Execution Environment

Interpreter Options and Environment

Interactive Sessions

Launching Python Applications

Site Configuration Files

Per-user Site Packages

Enabling Future Features

Program Termination

11   Testing, Debugging, Profiling, and Tuning

Documentation Strings and the doctest Module

Unit Testing and the unittest Module

The Python Debugger and the pdb Module

Debugger Commands

Debugging from the Command Line

Configuring the Debugger

Program Profiling

Tuning and Optimization

Making Timing Measurements

Making Memory Measurements

Disassembly

Tuning Strategies

II: The Python Library

12   Built-In Functions and Exceptions

Built-in Functions and Types

Built-In Exceptions

Exception Base Classes

Exception Instances

Predefined Exception Classes

Built-In Warnings

future_builtins

13   Python Runtime Services

atexit

copy

Notes

gc

Notes

inspect

marshal

Notes

pickle

Notes

sys

Variables

Functions

traceback

types

Notes

warnings

Notes

weakref

Example

Notes

14   Mathematics

decimal

Decimal Objects

Context Objects

Functions and Constants

Examples

Notes

fractions

math

Notes

numbers

Notes

random

Seeding and Initialization

Random Integers

Random Sequences

Real-Valued Random Distributions

Notes

15   Data Structures, Algorithms, and Code Simplification

abc

array

Notes

bisect

collections

deque and defaultdict

Named Tuples

Abstract Base Classes

contextlib

functools

heapq

itertools

Examples

operator

16   String and Text Handling

codecs

Low-Level codecs Interface

I/O-Related Functions

Useful Constants

Standard Encodings

Notes

re

Pattern Syntax

Functions

Regular Expression Objects

Match Objects

Example

Notes

string

Constants

Formatter Objects

Template Strings

Utility Functions

struct

Packing and Unpacking Functions

Struct Objects

Format Codes

Notes

unicodedata

17   Python Database Access

Relational Database API Specification

Connections

Cursors

Forming Queries

Type Objects

Error Handling

Multithreading

Mapping Results into Dictionaries

Database API Extensions

sqlite3 Module

Module-Level Functions

Connection Objects

Cursors and Basic Operations

DBM-Style Database Modules

shelve Module

18   File and Directory Handling

bz2

filecmp

fnmatch

Examples

glob

Example

gzip

Notes

shutil

tarfile

Exceptions

Example

tempfile

zipfile

zlib

19   Operating System Services

commands

Notes

configParser, Configparser

The ConfigParser Class

Example

Notes

datetime

date Objects

time Objects

datetime objects

timedelta objects

Mathematical Operations Involving Dates

tzinfo Objects

Date and Time Parsing

errno

POSIX Error Codes

Windows Error Codes

fcntl

Example

Notes

io

Base I/O Interface

Raw I/O

Buffered Binary I/O

Text I/O

The open() Function

Abstract Base Classes

logging

Logging Levels

Basic Configuration

Logger Objects

Handler Objects

Message Formatting

Miscellaneous Utility Functions

Logging Configuration

Performance Considerations

Notes

mmap

Notes

msvcrt

optparse

Example

Notes

os

Process Environment

File Creation and File Descriptors

Files and Directories

Process Management

System Configuration

Exceptions

os.path

signal

Example

Notes

subprocess

Examples

Notes

time

Notes

winreg

Notes

20   Threads and Concurrency

Basic Concepts

Concurrent Programming and Python

multiprocessing

Processes

Interprocess Communication

Process Pools

Shared Data and Synchronization

Managed Objects

Connections

Miscellaneous Utility Functions

General Advice on Multiprocessing

threading

Thread Objects

Timer Objects

Lock Objects

RLock

Semaphore and Bounded Semaphore

Events

Condition Variables

Working with Locks

Thread Termination and Suspension

Utility Functions

The Global Interpreter Lock

Programming with Threads

queue, Queue

Queue Example with Threads

Coroutines and Microthreading

21   Network Programming and Sockets

Network Programming Basics

asynchat

asyncore

Example

select

Advanced Module Features

Advanced Asynchronous I/O Example

When to Consider Asynchronous Networking

socket

Address Families

Socket Types

Addressing

Functions

Exceptions

Example

Notes

ssl

Examples

SocketServer

Handlers

Servers

Defining Customized Servers

Customization of Application Servers

22   Internet Application Programming

ftplib

Example

http Package

http.client (httplib)

http.server (BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer)

http.cookies (Cookie)

http.cookiejar (cookielib)

smtplib

Example

urllib Package

urllib.request (urllib2)

urllib.response

urllib.parse

urllib.error

urllib.robotparser (robotparser)

Notes

xmlrpc Package

xmlrpc.client (xmlrpclib)

xmlrpc.server (SimpleXMLRPCServer, DocXMLRPCServer)

23   Web Programming

cgi

CGI Programming Advice

Notes

cgitb

wsgiref

The WSGI Specification

wsgiref Package

webbrowser

24   Internet Data Handling and Encoding

base64

binascii

csv

Dialects

Example

email Package

Parsing Email

Composing Email

Notes

hashlib

hmac

Example

HTMLParser

Example

json

mimetypes

quopri

xml Package

XML Example Document

xml.dom.minidom

xml.etree.ElementTree

xml.sax

xml.sax.saxutils

25   Miscellaneous Library Modules

Python Services

String Processing

Operating System Modules

Network

Internet Data Handling

Internationalization

Multimedia Services

Miscellaneous

III: Extending and Embedding

26   Extending and Embedding Python

Extension Modules

An Extension Module Prototype

Naming Extension Modules

Compiling and Packaging Extensions

Type Conversion from Python to C

Type Conversion from C to Python

Adding Values to a Module

Error Handling

Reference Counting

Threads

Embedding the Python Interpreter

An Embedding Template

Compilation and Linking

Basic Interpreter Operation and Setup

Accessing Python from C

Converting Python Objects to C

ctypes

Loading Shared Libraries

Foreign Functions

Datatypes

Calling Foreign Functions

Alternative Type Construction Methods

Utility Functions

Example

Advanced Extending and Embedding

Jython and IronPython

Appendix   Python 3

Who Should Be Using Python 3?

New Language Features

Source Code Encoding and Identifiers

Set Literals

Set and Dictionary Comprehensions

Extended Iterable Unpacking

Nonlocal Variables

Function Annotations

Keyword-Only Arguments

Ellipsis as an Expression

Chained Exceptions

Improved super()

Advanced Metaclasses

Common Pitfalls

Text Versus Bytes

New I/O System

print() and exec() Functions

Use of Iterators and Views

Integers and Integer Division

Comparisons

Iterators and Generators

File Names, Arguments, and Environment Variables

Library Reorganization

Absolute Imports

Code Migration and 2to3

Porting Code to Python 2.6

Providing Test Coverage

Using the 2to3 Tool

A Practical Porting Strategy

Simultaneous Python 2 and Python 3 Support

Participate

Index

About the Author

David M. Beazley is a long-time Python enthusiast, having been involved with the Python community since 1996. He is probably best known for his work on SWIG, a popular software package for integrating C/C++ programs with other programming languages, including Python, Perl, Ruby, Tcl, and Java. He has also written a number of other programming tools, including PLY, a Python implementation of lex and yacc. Dave spent seven years working in the Theoretical Physics Division at Los Alamos National Laboratory, where he helped pioneer the use of Python with massively parallel supercomputers. After that, Dave went off to work as an evil professor, where he enjoyed tormenting college students with a variety of insane programming projects. However, he has since seen the error of his ways and is now working as an independent software developer, consultant, Python trainer, and occasional jazz musician living in Chicago. He can be contacted at http://www.dabeaz.com.

About the Technical Editor

Noah Gift is the co-author of Python For UNIX and Linux System Administration (O’Reilly) and is also working on Google App Engine In Action (Manning). He is an author, speaker, consultant, and community leader, writing for publications such as IBM developerWorks, Red Hat Magazine, O’Reilly, and MacTech. His consulting company’s website is http://www.giftcs.com, and much of his writing can be found at http://noahgift.com. You can also follow Noah on Twitter.

Noah has a master’s degree in CIS from Cal State, Los Angeles, a B.S. in nutritional science from Cal Poly San Luis Obispo, is an Apple and LPI-certified SysAdmin, and has worked at companies such as Caltech, Disney Feature Animation, Sony Imageworks, and Turner Studios. He is currently working at Weta Digital in New Zealand. In his free time he enjoys spending time with his wife Leah and their son Liam, composing for the piano, running marathons, and exercising religiously.

Acknowledgments

This book would not be possible without the support of many people. First and foremost, I’d like to thank Noah Gift for jumping into the project and providing his amazing feedback on the fourth edition. Kurt Grandis also provided useful comments for many chapters. I’d also like to acknowledge past technical reviewers Timothy Boronczyk, Paul DuBois, Mats Wichmann, David Ascher, and Tim Bell for their valuable comments and advice that made earlier editions a success. Guido van Rossum, Jeremy Hylton, Fred Drake, Roger Masse, and Barry Warsaw also provided tremendous assistance with the first edition while hosting me for a few weeks back in the hot summer of 1999. Last, but not least, this book would not be possible without all of the feedback I received from readers. There are far too many people to list individually, but I have done my best to incorporate your suggestions for making the book even better. I’d also like to thank all the folks at Addison-Wesley and Pearson Education for their continued commitment to the project and assistance. Mark Taber, Michael Thurston, Seth Kerney, and Lisa Thibault all helped out to get this edition out the door in good shape. A special thanks is in order for Robin Drake, whose tremendous effort in editing previous editions made the third edition possible. Finally, I’d like to acknowledge my amazing wife and partner Paula Kamen for all of her encouragement, diabolical humor, and love.

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way.

You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book’s title and author as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book.

Email:      [email protected]

Mail:        Mark Taber
                Associate Publisher
                Pearson Education
                800 East 96th Street
                Indianapolis, IN 46240 USA

Reader Services

Visit our website and register this book at informit.com/register for convenient access to any updates, downloads, or errata that might be available for this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251