Chapter 1 Python Shortcuts
Introduction
Swapping Values WithoutUsing a Temporary Variable
Constructing a Dictionary Without Excessive Quoting
Getting a Value from a Dictionary
Adding an Entry to a Dictionary
Associating Multiple Values with Each Key in a Dictionary
Dispatching Using a Dictionary
Collecting a Bunch of Named Items
Finding the Intersection of Two Dictionaries
Assigning and Testing with One Statement
Using List Comprehensions Instead of map and filter
Unzipping Simple List-Like Objects
Flattening a Nested Sequence
Looping in Parallel over Index and Sequence Items
Looping Through Multiple Lists
Spanning a Range Defined by Floats
Transposing Two-Dimensional Arrays
Creating Lists of Lists Without Sharing References
Chapter 2 Searching and Sorting
Introduction
Sorting a Dictionary
Processing Selected Pairs of Structured Data Efficiently
Sorting While Guaranteeing Sort Stability
Sorting by One Field, Then by Another
Looking for Items in a Sorted Sequence Using Binary Search
Sorting a List of Objects by an Attribute of the Objects
Sorting by Item or by Attribute
Selecting Random Elements from a List Without Repetition
Performing Frequent Membership Tests on a Sequence
Finding the Deep Index of an Item in an Embedded Sequence
Showing Off Quicksort in Three Lines
Sorting Objects Using SQL’s ORDER BY Syntax
Chapter 3 Text
Introduction
Processing a String One Character at a Time
Testing if an Object Is String-Like
Aligning Strings
Trimming Space from the Ends of a String
Combining Strings
Checking Whether a String Contains a Set of Characters
Filtering a String for a Set of Characters
Controlling Case
Reversing a String by Words or Characters
Accessing Substrings
Changing the Indentation of a Multiline String
Testing Whether a String Represents an Integer
Expanding and Compressing Tabs
Replacing Multiple Patterns in a Single Pass
Converting Between Different Naming Conventions
Converting Between Characters and Values
Converting Between Unicode and Plain Strings
Printing Unicode Characters to Standard Output
Dispatching Based on Pattern Matches
Evaluating Code Inside Strings
Replacing Python Code with the Results of Executing That Code
Module: Yet Another Python Templating Utility (YAPTU)
Module: Roman Numerals
Chapter 4 Files
Introduction
Reading from a File
Writing to a File
Searching and Replacing Text in a File
Reading a Particular Line from a File
Retrieving a Line at Random from a File of Unknown Size
Counting Lines in a File
Processing Every Word in a File
Reading a Text File by Paragraphs
Reading Lines with Continuation Characters
Reading Data from ZIP Files
Reading INI Configuration Files
Sending Binary Data to Standard Output Under Windows
Using Random-Access Input/Output
Updating a Random-Access File
Splitting a Path into All of Its Parts
Treating Pathnames as Objects
Creating Directories Including Necessary Parent Directories
Walking Directory Trees
Swapping One File Extension for Another Throughout a Directory Tree
Finding a File Given an Arbitrary Search Path
Finding a File on the Python Search Path
Dynamically Changing the Python Search Path
Computing Directory Sizes in a Cross-Platform Way
File Locking Using a Cross-Platform API
Versioning Filenames
Module: Versioned Backups
Chapter 5 Object-Oriented Programming
Introduction
Overriding a Built-In Method
Getting All Members of a Class Hierarchy
Calling a Superclass _ _init_ _ Method if It Exists
Calling a Superclass Implementation of a Method
Implementing Properties
Implementing Static Methods
Implementing Class Methods
Delegating Automatically as an Alternative to Inheritance
Decorating an Object with Print-Like Methods
Checking if an Object Has Necessary Attributes
Making a Fast Copy of an Object
Adding Methods to a Class at Runtime
Modifying the Class Hierarchy of an Instance
Keeping References to Bound Methods Without Inhibiting Garbage Collection
Defining Constants
Managing Options
Implementing a Set Class
Implementing a Ring Buffer
Implementing a Collection
Delegating Messages to Multiple Objects
Implementing the Singleton Design Pattern
Avoiding the Singleton Design Pattern with the Borg Idiom
Implementing the Null Object Design Pattern
Chapter 6 Threads, Processes, and Synchronization
Introduction
Storing Per-Thread Information
Terminating a Thread
Allowing Multithreaded Read Access While Maintaining a Write Lock
Running Functions in the Future
Synchronizing All Methods in an Object
Capturing the Output and Error Streams from a Unix Shell Command
Forking a Daemon Process on Unix
Determining if Another Instance of a Script Is Already Running in Windows
Processing Windows Messages Using MsgWaitForMultipleObjects
Chapter 7 System Administration
Introduction
Running a Command Repeatedly
Generating Random Passwords
Generating Non-Totally Random Passwords
Checking the Status of a Unix Network Interface
Calculating Apache Hits per IP Address
Calculating the Rate of Client Cache Hits on Apache
Manipulating the Environment on Windows NT/2000/XP
Checking and Modifying the Set of Tasks Windows Automatically Runs at Logon
Examining the Microsoft Windows Registry for a List of Name Server Addresses
Getting Information About the Current User on Windows NT/2000
Getting the Windows Service Name from Its Long Name
Manipulating Windows Services
Impersonating Principals on Windows
Changing a Windows NT Password Using ADSI
Working with Windows Scripting Host (WSH) from Python
Displaying Decoded Hotkeys for Shortcuts in Windows
Chapter 8 Databases and Persistence
Introduction
Serializing Data Using the marshal Module
Serializing Data Using the pickle and cPickle Modules
Using the cPickle Module on Classes and Instances
Mutating Objects with shelve
Accessing a MySQL Database
Storing a BLOB in a MySQL Database
Storing a BLOB in a PostgreSQL Database
Generating a Dictionary Mapping from Field Names to Column Numbers
Using dtuple for Flexible Access to Query Results
Pretty-Printing the Contents of Database Cursors
Establishing Database Connections Lazily
Accessing a JDBC Database from a Jython Servlet
Module: jet2sql—Creating a SQL DDL from an Access Database
Chapter 9 User Interfaces
Introduction
Avoiding lambda in Writing Callback Functions
Creating Menus with Tkinter
Creating Dialog Boxes with Tkinter
Supporting Multiple Values per Row in a Tkinter Listbox
Embedding Inline GIFs Using Tkinter
Combining Tkinter and Asynchronous I/O with Threads
Using a wxPython Notebook with Panels
Giving the User Unobtrusive Feedback During Data Entry with Qt
Building GUI Solutions Independent of the Specific GUI Toolkit
Creating Color Scales
Using Publish/Subscribe Broadcasting to Loosen the Coupling Between GUI and Business Logic Systems
Module: Building GTK GUIs Interactively
Chapter 10 Network Programming
Introduction
Writing a TCP Client
Writing a TCP Server
Passing Messages with Socket Datagrams
Finding Your Own Name and Address
Converting IP Addresses
Grabbing a Document from the Web
Being an FTP Client
Sending HTML Mail
Sending Multipart MIME Email
Bundling Files in a MIME Message
Unpacking a Multipart MIME Message
Module: PyHeartBeat—Detecting Inactive Computers
Module: Interactive POP3 Mailbox Inspector
Module: Watching for New IMAP Mail Using a GUI
Chapter 11 Web Programming
Introduction
Testing Whether CGI Is Working
Writing a CGI Script
Using a Simple Dictionary for CGI Parameters
Handling URLs Within a CGI Script
Resuming the HTTP Download of a File
Stripping Dangerous Tags and Javascript from HTML
Running a Servlet with Jython
Accessing Netscape Cookie Information
Finding an Internet Explorer Cookie
Module: Fetching Latitude/Longitude Data from the Web
Chapter 12 Processing XML
Introduction
Checking XML Well-Formedness
Counting Tags in a Document
Extracting Text from an XML Document
Transforming an XML Document Using XSLT
Transforming an XML Document Using Python
Parsing an XML File with xml.parsers.expat
Converting Ad-Hoc Text into XML Markup
Normalizing an XML Document
Controlling XSLT Stylesheet Loading
Autodetecting XML Encoding
Module: XML Lexing (Shallow Parsing)
Module: Converting a List of Equal-Length Lists into XML
Chapter 13 Distributed Programming
Introduction
Making an XML-RPC Method Call
Serving XML-RPC Requests
Using XML-RPC with Medusa
Writing a Web Service That Supports Both XML-RPC and SOAP
Implementing a CORBA Client and Server
Performing Remote Logins Using telnetlib
Using Publish/Subscribe in a Distributed Middleware Architecture
Using Request/Reply in a Distributed Middleware Architecture
Chapter 14 Debugging and Testing
Introduction
Reloading All Loaded Modules
Tracing Expressions and Comments in Debug Mode
Wrapping Tracebacks in HTML
Getting More Information from Tracebacks
Starting the Debugger Automatically After an Uncaught Exception
Logging and Tracing Across Platforms
Determining the Name of the Current Function
Introspecting the Call Stack with Older Versions of Python
Debugging the Garbage-Collection Process
Tracking Instances of Particular Classes
Chapter 15 Programs About Programs
Introduction
Colorizing Python Source Using the Built-in Tokenizer
Importing a Dynamically Generated Module
Importing from a Module Whose Name Is Determined at Runtime
Importing Modules with Automatic End-of-Line Conversions
Simulating Enumerations in Python
Modifying Methods in Place
Associating Parameters with a Function (Currying)
Composing Functions
Adding Functionality to a Class
Adding a Method to a Class Instance at Runtime
Defining a Custom Metaclass to Control Class Behavior
Module: Allowing the Python Profiler to Profile C Modules
Chapter 16 Extending and Embedding
Introduction
Implementing a Simple Extension Type
Translating a Python Sequence into a C Array with the PySequence_Fast Protocol
Accessing a Python Sequence Item-by-Item with the Iterator Protocol
Returning None from a Python-Callable C Function
Coding the Methods of a Python Class in C
Implementing C Function Callbacks to a Python Function
Debugging Dynamically Loaded C Extensions with gdb
Debugging Memory Problems
Using SWIG-Generated Modules in a Multithreaded Environment
Chapter 17 Algorithms
Introduction
Testing if a Variable Is Defined
Evaluating Predicate Tests Across Sequences
Removing Duplicates from a Sequence
Removing Duplicates from a Sequence While Maintaining Sequence Order
Simulating the Ternary Operator in Python
Counting Items and Sorting by Incidence (Histograms)
Memoizing (Caching) the Return Values of Functions
Looking Up Words by Sound Similarity
Computing Factorials with lambda
Generating the Fibonacci Sequence
Wrapping an Unbounded Iterator to Restrict Its Output
Operating on Iterators
Rolling Dice
Implementing a First-In First-Out Container
Modeling a Priority Queue
Converting Numbers to Rationals via Farey Fractions
Evaluating a Polynomial
Module: Finding the Convex Hull of a Set of 2D Points
Module: Parsing a String into a Date/Time Object Portably
Autocomplete with Trie Tree -- code in python
9 years ago
Post a Comment