Python Cookbook, 2nd Ed.
Recipes from the Python Community
Publisher: O'Reilly, 2005 , 807 pages
ISBN: 0-596-00797-3
Synopsis:
- Toggle Synopsis
-
Covers Python 2.3 & 2.4
Python is well-known as a robust and elegant language, with support for both functional and object-oriented programming styles. When you choose to use Python, however, you get more than just a language-you also become part of an incredibly enthusiastic and supportive community of Python programmers who reach out to help each other learn and grow in their use of the language. Python Cookbook, 2nd Edition is just one tangible manifestation of that Python community. In it, you'll find practical solutions to many common Python programming problems. These solutions come from the community, from Python programmers who for many years have contributed to the online Python Cookbook hosted by ActiveState at http://aspn.activestate.com/ASPN/Cookbook/Python. These are battle-tested solutions; contributed, reviewed, enhanced, and now brought together in book form. Here is just a sampling of the many topic areas covered by the more than 300 recipes in this book:
- Searching and sorting
- Manipulating text
- Working with files
- Object-oriented programming
- Multithreaded programming
- System administration
- Web programming
- Network programming
- Processing XML
- Distributed programming
- Debugging and testing
- Metaprogramming
Solutions in this book are organized by topic area. All of the chapters begin with introductions written by well-known Python luminaries such as: Facundo Batista, David Beazley, Donn Cave, Fred L. Drake, Jr., Paul F. Dubois, Mark Hammond, Raymond Hettinger, Jeremy Hylton, Fredrik Lundh, Mark Lutz, Andy McKay, Gustavo Niemeyer, Tim Peters, Paul Prescod, Aaron Watters, and Greg Wilson.
This book is a treasure trove of useful code for all Python programmers, from novices to advanced practitioners. It's a gift, from the community to you. By purchasing this book, you are also giving back to the community: 25 percent of all royalties from this book are donated to the Python Software Foundation.
Table of Contents:
- Toggle Table of Contents
-
- Text
- Processing a String One Character at a Time
- Converting Between Characters and Numeric Codes
- Testing Whether an Object Is String-like
- Aligning Strings
- Trimming Space from the Ends of a String
- Combining Strings
- Reversing a String by Words or Characters
- Checking Whether a String Contains a Set of Characters
- Simplifying Usage of Strings' translate Method
- Filtering a String for a Set of Characters
- Checking Whether a String Is Text or Binary
- Controlling Case
- Accessing Substrings
- Changing the Indentation of a Multiline String
- Expanding and Compressing Tabs
- Interpolating Variables in a String
- Interpolating Variables in a String in Python 2.4
- Replacing Multiple Patterns in a Single Pass
- Checking a String for Any of Multiple Endings
- Handling International Text with Unicode
- Converting Between Unicode and Plain Strings
- Printing Unicode Characters to Standard Output
- Encoding Unicode Data for XML and HTML
- Making Some Strings Case-Insensitive
- Converting HTML Documents to Text on a Unix Terminal
- Files
- Reading from a File
- Writing to a File
- Searching and Replacing Text in a File
- Reading a Specific Line from a File
- Counting Lines in a File
- Processing Every Word in a File
- Using Random-Access Input/Output
- Updating a Random-Access File
- Reading Data from zip Files
- Handling a zip File Inside a String
- Archiving a Tree of Files into a Compressed tar File
- Sending Binary Data to Standard Output Under Windows
- Using a C++-like iostream Syntax
- Rewinding an Input File to the Beginning
- Adapting a File-like Object to a True File Object
- Walking Directory Trees
- Swapping One File Extension for Another Throughout a Directory Tree
- Finding a File Given a Search Path
- Finding Files Given a Search Path and a Pattern
- Finding a File on the Python Search Path
- Dynamically Changing the Python Search Path
- Computing the Relative Path from One Directory to Another
- Reading an Unbuffered Character in a Cross-Platform Way
- Counting Pages of PDF Documents on Mac OS X
- Changing File Attributes on Windows
- Extracting Text from OpenOffice.org Documents
- Extracting Text from Microsoft Word Documents
- File Locking Using a Cross-Platform API
- Versioning Filenames
- Calculating CRC-64 Cyclic Redundancy Checks
- Time and Money
- Calculating Yesterday and Tomorrow
- Finding Last Friday
- Calculating Time Periods in a Date Range
- Summing Durations of Songs
- Calculating the Number of Weekdays Between Two Dates
- Looking up Holidays Automatically
- Fuzzy Parsing of Dates
- Checking Whether Daylight Saving Time Is Currently in Effect
- Converting Time Zones
- Running a Command Repeatedly
- Scheduling Commands
- Doing Decimal Arithmetic
- Formatting Decimals as Currency
- Using Python as a Simple Adding Machine
- Checking a Credit Card Checksum
- Watching Foreign Exchange Rates
- Python Shortcuts
- Copying an Object
- Constructing Lists with List Comprehensions
- Returning an Element of a List If It Exists
- Looping over Items and Their Indices in a Sequence
- Creating Lists of Lists Without Sharing References
- Flattening a Nested Sequence
- Removing or Reordering Columns in a List of Rows
- Transposing Two-Dimensional Arrays
- Getting a Value from a Dictionary
- Adding an Entry to a Dictionary
- Building a Dictionary Without Excessive Quoting
- Building a Dict from a List of Alternating Keys and Values
- Extracting a Subset of a Dictionary
- Inverting a Dictionary
- Associating Multiple Values with Each Key in a Dictionary
- Using a Dictionary to Dispatch Methods or Functions
- Finding Unions and Intersections of Dictionaries
- Collecting a Bunch of Named Items
- Assigning and Testing with One Statement
- Using printf in Python
- Randomly Picking Items with Given Probabilities
- Handling Exceptions Within an Expression
- Ensuring a Name Is Defined in a Given Module
- Searching and Sorting
- Sorting a Dictionary
- Sorting a List of Strings Case-Insensitively
- Sorting a List of Objects by an Attribute of the Objects
- Sorting Keys or Indices Based on the Corresponding Values
- Sorting Strings with Embedded Numbers
- Processing All of a List's Items in Random Order
- Keeping a Sequence Ordered as Items Are Added
- Getting the First Few Smallest Items of a Sequence
- Looking for Items in a Sorted Sequence
- Selecting the nth Smallest Element of a Sequence
- Showing off quicksort in Three Lines
- Performing Frequent Membership Tests on a Sequence
- Finding Subsequences
- Enriching the Dictionary Type with Ratings Functionality
- Sorting Names and Separating Them by Initials
- Object-Oriented Programming
- Converting Among Temperature Scales
- Defining Constants
- Restricting Attribute Setting
- Chaining Dictionary Lookups
- Delegating Automatically as an Alternative to Inheritance
- Delegating Special Methods in Proxies
- Implementing Tuples with Named Items
- Avoiding Boilerplate Accessors for Properties
- Making a Fast Copy of an Object
- Keeping References to Bound MethodsWithout Inhibiting Garbage Collection
- Implementing a Ring Buffer
- Checking an Instance for Any State Changes
- Checking Whether an Object Has Necessary Attributes
- Implementing the State Design Pattern
- Implementing the "Singleton" Design Pattern
- Avoiding the "Singleton" Design Pattern with the Borg Idiom
- Implementing the Null Object Design Pattern
- Automatically Initializing Instance Variablesfrom _ _init__ Arguments
- Calling a Superclass _ _init_ _ Method If It Exists
- Using Cooperative Supercalls Concisely and Safely
- Persistence and Databases
- Serializing Data Using the marshal Module
- Serializing Data Using the pickle and cPickle Modules
- Using Compression with Pickling
- Using the cPickle Module on Classes and Instances
- Holding Bound Methods in a Picklable Way
- Pickling Code Objects
- Mutating Objects with shelve
- Using the Berkeley DB Database
- Accesssing a MySQL Database
- Storing a BLOB in a MySQL Database
- Storing a BLOB in a PostgreSQL Database
- Storing a BLOB in a SQLite Database
- Generating a Dictionary Mapping Field Names to Column Numbers
- Using dtuple for Flexible Accessto Query Results
- Pretty-Printing the Contents of Database Cursors
- Using a Single Parameter-Passing StyleAcross Various DB API Modules
- Using Microsoft Jet via ADO
- Accessing a JDBC Database from a Jython Servlet
- Using ODBC to Get Excel Data with Jython
- Debugging and Testing
- Disabling Execution of Some Conditionals and Loops
- Measuring Memory Usage on Linux
- Debugging the Garbage-Collection Process
- Trapping and Recording Exceptions
- Tracing Expressions and Comments in Debug Mode
- Getting More Information from Tracebacks
- Starting the Debugger Automatically After an Uncaught Exception
- Running Unit Tests Most Simply
- Running Unit Tests Automatically
- Using doctest with unittest in Python 2.4
- Checking Values Against Intervals in Unit Testing
- Processes, Threads, and Synchronization
- Synchronizing All Methods in an Object
- Terminating a Thread
- Using a Queue.Queue as a Priority Queue
- Working with a Thread Pool
- Executing a Function in Parallel on Multiple Argument Sets
- Coordinating Threads by Simple Message Passing
- Storing Per-Thread Information
- Multitasking Cooperatively Without Threads
- Determining Whether Another Instance of a ScriptIs Already Running in Windows
- Processing Windows Messages Using MsgWaitForMultipleObjects
- Driving an External Process with popen
- Capturing the Output and Error Streamsfrom a Unix Shell Command
- Forking a Daemon Process on Unix
- System Administration
- Generating Random Passwords
- Generating Easily Remembered Somewhat-Random Passwords
- Authenticating Users by Means of a POP Server
- Calculating Apache Hits per IP Address
- Calculating the Rate of Client Cache Hits on Apache
- Spawning an Editor from a Script
- Backing Up Files
- Selectively Copying a Mailbox File
- Building a Whitelist of Email Addresses From a Mailbox
- Blocking Duplicate Mails
- Checking Your Windows Sound System
- Registering or Unregistering a DLL on Windows
- Checking and Modifying the Set of Tasks Windows Automatically Runs at Login
- Creating a Share on Windows
- Connecting to an Already Running Instance of Internet Explorer
- Reading Microsoft Outlook Contacts
- Gathering Detailed System Information on Mac OS X
- User Interfaces
- Showing a Progress Indicator on a Text Console
- Avoiding lambda in Writing Callback Functions
- Using Default Values and Bounds with tkSimpleDialog Functions
- Adding Drag and Drop Reordering to a Tkinter Listbox
- Entering Accented Characters in Tkinter Widgets
- Embedding Inline GIFs Using Tkinter
- Converting Among Image Formats
- Implementing a Stopwatch in Tkinter
- Combining GUIs and Asynchronous I/O with Threads
- Using IDLE's Tree Widget in Tkinter
- Supporting Multiple Values per Row in a Tkinter Listbox
- Copying Geometry Methods and Options Between Tkinter Widgets
- Implementing a Tabbed Notebook for Tkinter
- Using a wxPython Notebook with Panels
- Implementing an ImageJ Plug-in in Jython
- Viewing an Image from a URL with Swing and Jython
- Getting User Input on Mac OS
- Building a Python Cocoa GUI Programmatically
- Implementing Fade-in Windows with IronPython
- Processing XML
- Checking XML Well-Formedness
- Counting Tags in a Document
- Extracting Text from an XML Document
- Autodetecting XML Encoding
- Converting an XML Document into a Tree of Python Objects
- Removing Whitespace-only Text Nodesfrom an XML DOM Node's Subtree
- Parsing Microsoft Excel's XML
- Validating XML Documents
- Filtering Elements and Attributes Belonging to a Given Namespace
- Merging Continuous Text Events with a SAX Filter
- Using MSHTML to Parse XML or HTML
- Network Programming
- Passing Messages with Socket Datagrams
- Grabbing a Document from the Web
- Filtering a List of FTP Sites
- Getting Time from a Server via the SNTP Protocol
- Sending HTML Mail
- Bundling Files in a MIME Message
- Unpacking a Multipart MIME Message
- Removing Attachments from an Email Message
- Fixing Messages Parsed by Python 2.4 email.FeedParser
- Inspecting a POP3 Mailbox Interactively
- Detecting Inactive Computers
- Monitoring a Network with HTTP
- Forwarding and Redirecting Network Ports
- Tunneling SSL Through a Proxy
- Implementing the Dynamic IP Protocol
- Connecting to IRC and Logging Messages to Disk
- Accessing LDAP Servers
- Web Programming
- Testing Whether CGI Is Working
- Handling URLs Within a CGI Script
- Uploading Files with CGI
- Checking for a Web Page's Existence
- Checking Content Type via HTTP
- Resuming the HTTP Download of a File
- Handling Cookies While Fetching Web Pages
- Authenticating with a Proxy for HTTPS Navigation
- Running a Servlet with Jython
- Finding an Internet Explorer Cookie
- Generating OPML Files
- Aggregating RSS Feeds
- Turning Data into Web Pages Through Templates
- Rendering Arbitrary Objects with Nevow
- Distributed Programming
- Making an XML-RPC Method Call
- Serving XML-RPC Requests
- Using XML-RPC with Medusa
- Enabling an XML-RPC Server to Be Terminated Remotely
- Implementing SimpleXMLRPCServer Niceties
- Giving an XML-RPC Server a wxPython GUI
- Using Twisted Perspective Broker
- Implementing a CORBA Server and Client
- Performing Remote Logins Using telnetlib
- Performing Remote Logins with SSH
- Authenticating an SSL Client over HTTPS
- Programs About Programs
- Verifying Whether a String Represents a Valid Number
- Importing a Dynamically Generated Module
- Importing from a Module Whose Name Is Determined at Runtime
- Associating Parameters with a Function (Currying)
- Composing Functions
- Colorizing Python Source Using the Built-in Tokenizer
- Merging and Splitting Tokens
- Checking Whether a String Has Balanced Parentheses
- Simulating Enumerations in Python
- Referring to a List Comprehension While Building It
- Automating the py2exe Compilationof Scripts into Windows Executables
- Binding Main Script and Modules into One Executable on Unix
- Extending and Embedding
- Implementing a Simple Extension Type
- Implementing a Simple Extension Type with Pyrex
- Exposing a C++ Library to Python
- Calling Functions from a Windows DLL
- Using SWIG-Generated Modules in a Multithreaded Environment
- Translating a Python Sequence into a C Arraywith the PySequence_Fast Protocol
- Accessing a Python Sequence Item-by-Item with the Iterator Protocol
- Returning None from a Python-Callable C Function
- Debugging Dynamically Loaded C Extensions with gdb
- Debugging Memory Problems
- Algorithms
- Removing Duplicates from a Sequence
- Removing Duplicates from a SequenceWhile Maintaining Sequence Order
- Generating Random Samples with Replacement
- Generating Random Samples Without Replacement
- Memoizing (Caching) the Return Values of Functions
- Implementing a FIFO Container
- Caching Objects with a FIFO Pruning Strategy
- Implementing a Bag (Multiset) Collection Type
- Simulating the Ternary Operator in Python
- Computing Prime Numbers
- Formatting Integers as Binary Strings
- Formatting Integers as Strings in Arbitrary Bases
- Converting Numbers to Rationals via Farey Fractions
- Doing Arithmetic with Error Propagation
- Summing Numbers with Maximal Accuracy
- Simulating Floating Point
- Computing the Convex Hulls and Diameters of 2D Point Sets
- Iterators and Generators
- Writing a range-like Function with Float Increments
- Building a List from Any Iterable
- Generating the Fibonacci Sequence
- Unpacking a Few Items in a Multiple Assignment
- Automatically Unpacking the Needed Number of Items
- Dividing an Iterable into n Slices of Stride n
- Looping on a Sequence by Overlapping Windows
- Looping Through Multiple Iterables in Parallel
- Looping Through the Cross-Product of Multiple Iterables
- Reading a Text File by Paragraphs
- Reading Lines with Continuation Characters
- Iterating on a Stream of Data Blocks as a Stream of Lines
- Fetching Large Record Sets from a Database with a Generator
- Merging Sorted Sequences
- Generating Permutations, Combinations, and Selections
- Generating the Partitions of an Integer
- Duplicating an Iterator
- Looking Ahead into an Iterator
- Simplifying Queue-Consumer Threads
- Running an Iterator in Another Thread
- Computing a Summary Report with itertools.groupby
- Descriptors, Decorators, and Metaclasses
- Getting Fresh Default Values at Each Function Call
- Coding Properties as Nested Functions
- Aliasing Attribute Values
- Caching Attribute Values
- Using One Method as Accessor for Multiple Attributes
- Adding Functionality to a Class by Wrapping a Method
- Adding Functionality to a Class by Enriching All Methods
- Adding a Method to a Class Instance at Runtime
- Checking Whether Interfaces Are Implemented
- Using _ _new_ _ and _ _init_ _ Appropriately in Custom Metaclasses
- Allowing Chaining of Mutating List Methods
- Using Cooperative Supercalls with Terser Syntax
- Initializing Instance Attributes Without Using _ _init_ _
- Automatic Initialization of Instance Attributes
- Upgrading Class Instances Automatically on reload
- Binding Constants at Compile Time
- Solving Metaclass Conflicts
Reviews:
Python Cookbook
Rating: ******* (Good)
Collection of solutions.
A very good tool for learning new techniques or just get another perspectives on stuff. I really liked it. But be warned that you need to know Python and be a serious programmer, as this seems to be the intended audience for this book.
Python Essential Reference