Chapter Persistence and Databases

Serializing Data Using the marshal Module Recipe 7.2. Serializing Data Using the pickle and cPickle Modules Recipe 7.3. Using Compression with Pickling Recipe 7.4. Using the cPickle Module on Classes and Instances Recipe 7.5. Holding Bound Methods in a Picklable Way Recipe 7.6. Pickling Code Objects Recipe 7.7. Mutating Objects with shelve Recipe 7.8. Using the Berkeley DB Database Recipe 7.9. Accesssing a MySQL Database Recipe 7.10. Storing a BLOB in a MySQL Database Recipe 7.11....

Alex Martelli

I first met Python thanks to the gentle insistence of a former colleague, Alessandro Bottoni. He kept courteously repeating that I really should give Python a try, in spite of my claims that I already knew more programming languages than I knew what to do with. If I hadn't trusted his technical and aesthetic judgment enough to invest the needed time and energy on the basis of his suggestion, I most definitely wouldn't be writing and editing Python books today. Thanks for your well-placed...

Chapter Debugging and Testing

Disabling Execution of Some Conditionals and Loops Recipe 8.2. Measuring Memory Usage on Linux Recipe 8.3. Debugging the Garbage-Collection Process Recipe 8.4. Trapping and Recording Exceptions Recipe 8.5. Tracing Expressions and Comments in Debug Mode Recipe 8.6. Getting More Information from Tracebacks Recipe 8.7. Starting the Debugger Automatically After an Uncaught Exception Recipe 8.8. Running Unit Tests Most Simply Recipe 8.9. Running Unit Tests Automatically Recipe 8.10....

Chapter Object Oriented Programming

Converting Among Temperature Scales Recipe 6.3. Restricting Attribute Setting Recipe 6.4. Chaining Dictionary Lookups Recipe 6.5. Delegating Automatically as an Alternative to Inheritance Recipe 6.6. Delegating Special Methods in Proxies Recipe 6.7. Implementing Tuples with Named Items Recipe 6.8. Avoiding Boilerplate Accessors for Properties Recipe 6.9. Making a Fast Copy of an Object Recipe 6.10. Keeping References to Bound Methods Without Inhibiting Garbage Collection Recipe...

David Ascher

The software that runs the online cookbook was the product of Andy McKay's constant and diligent effort. Andy was ActiveState's key Zope developer during the online data-collection phase of this project, and one of the key developers behind ASPN (http aspn.activestate.com), ActiveState's content site, which serves a wide variety of information for and by programmers of open source languages such as Python, Perl, PHP, Tcl, and XSLT. Andy McKay used to be a Perl developer, by the way. At about...

Discussion

As per usual Python practice, we can complete this module with a small self-test, executed only when the module is run as main script. This snippet also serves to show how the module's functionality can be used if _ _name_ _ '_ _main_ _' import threading import time class Dummy(object) def foo(self) print 'hello from foo' time.sleep(l) def bar(self) print 'hello from bar' def baaz(self) print 'hello from baaz' tw SynchronizedObject(Dummy( ), ignore 'baaz' ) threading.Thread(target...

However in some cases you may be able to do something about it

Self.stuff stuff def _ _getstate_ _(self) def normalize(x) return 1, (x.name, x.mode, x.tell( )) return 0, x return normalize(x) for x in self.stuff def _ _setstate_ _(self, stuff) def reconstruct(x) if x 0 0 return x 1 name, mode, offs x 1 openfile open(name, mode) openfile.seek(offs) return openfile self.stuff tuple( reconstruct(x) for x in stuff ) By defining the__getstate__and__setstate__special methods in your class, you gain fine-grained control about what, exactly, your class' instances...

Index

SYMBOL A B C D E F G H J J K L M N O P Q R S J U V W X Z EAFP (easier to ask forgiveness than permission) email addresses, building whitelist of, from mailboxes email messages blocking duplicates in Python 2.4 logging to disk malformed POP3 mailboxes 2nd removing attachments from email module email package bundling files in MIME messages embedding Python empty string joiner ( .join) 2nd encoding types of Unicode for XML HTML XML, autodetecting enumerate function enumerations, simulating eq...

Introduction

Thirty years ago, in his classic The Mythical Man-Month Essays on Software Engineering (Addison-Wesley), Fred Brooks drew a distinction between accidental and intrinsic complexity. Languages such as English and C++, with their inconsistent rules, exceptions, and special cases, are examples of the former they make communication and programming harder than they need to be. Concurrency, on the other hand, is a prime example of the latter. Most people have to struggle to keep one chain of events...

Organization

Each chapter is devoted to a particular kind of recipe, such as algorithms, text processing, databases, and so on. The 1st edition had 17 chapters. There have been improvements to Python, both language and library, and to the corpus of recipes the Python community has posted to the cookbook site, that convinced us to add three entirely new chapters on the iterators and generators introduced in Python 2.3 on Python's support for time and money operations, both old and...

Problem

You have Microsoft Excel spreadsheets saved in XML form, and want to parse them into memory as Python nested lists. The XML form of Excel spreadsheets is quite simple all text is in Cell tags, which are nested in Row tags nested in Table tags. SAX makes it quite simple to parse this kind of XML into memory from xml.sax import saxutils, parse class ExcelHandler(saxutils.DefaultHandler) def _ _init_ _(self) self.chars self.cells self.rows self.tables def characters(self, content)...

Python calls it automatically when a lookup for any attribute including a methodPython draws no distinction there has

In the old-style (classic) object model,__getattr__also applied to special methods that were looked up as part of a Python operation. This required some care to avoid mistakenly supplying a special method one didn't really want to supply but was otherwise handy. Nowadays, the new-style object model is recommended for all new code it is faster, more regular, and richer in features. You get new-style classes when you subclass object or any other built-in type. One day, some years from now, Python...

See Also

Unicode is a huge topic, but a recommended book is Tony Graham, Unicode A Primer (Hungry Minds)details are available at and a short, but complete article from Joel Spolsky, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses) is located at See also the Library Reference and Python in a Nutshell documentation about the built-in str and unicode types, and modules unidata and codecs also, Recipe 1.20 and Recipe 1.22.

Solution

Interfaces and adapters are the Twisted and Nevow approach to this task. Here is a toy example web server script to show how they work from twisted.application import internet, service from nevow import appserver, compy, inevow, loaders, rend Define some simple classes to be the example's application data class Person(object) def _ _init_ _(self, firstName, lastName, nickname) self.firstName firstName self.lastName lastName self.nickname nickname class Bookmark(object) def _ _init_ _(self,...

The time Module

Python Standard Library's time module lets Python applications access a good portion of the time-related functionality offered by the platform Python is running on. Your platform's documentation for the equivalent functions in the C library will therefore be useful, and some peculiarities of different platforms will affect Python as well. One of the most used functions from module time is the one that obtains the current timetime.time. This function's return value may be a little cryptic for...

What Is a Sequence

Python does not have a specific type called sequence, but sequence is still an often-used term in Python. sequence, strictly speaking, means a container that can be iterated on, to get a finite number of items, one at a time, and that also supports indexing, slicing, and being passed to the built-in function len (which gives the number of items in a container). Python lists are the sequences you'll meet most often, but there are many others (strings, unicode objects, tuples, array.arrays,...

With this enriched version of Borg the examples output changes to

The Singleton Design Pattern has a catchy name, but unfortunately it also has the wrong focus for most purposes it focuses on object identity, rather than on object state and behavior. The Borg design nonpattern makes all instances share state instead, and Python makes implementing this idea a snap. In most cases in which you might think of using Singleton or Borg, you don't really need either of them. Just write a Python module, with functions and module-global variables, instead of defining a...