next up previous contents
Next: Copying Objects Up: Object Persistency and Previous: Object Persistency and

Persistent Objects

The module pickle provides a general framework for objects to disassemble themselves into a stream of bytes and to reassemble such a stream back into an object. It copes with reference sharing, recursive objects and instances of user-defined classes, but not (directly) with objects that have ``magical'' links into the operating system such as open files, sockets or windows.

The pickle module defines a simple protocol whereby user-defined classes can control how they are disassembled and assembled. The method __getinitargs__(), if defined, returns the argument list for the constructor to be used at assembly time (by default the constructor is called without arguments). The methods __getstate__() and __setstate__() are used to pass additional state from disassembly to assembly; by default the instance's __dict__ is passed and restored.

Note that pickle does not open or close any files --- it can be used equally well for moving objects around on a network or store them in a database. For ease of debugging, and the inevitable occasional manual patch-up, the constructed byte streams consist of printable ASCII characters only (though it's not designed to be pretty).

The module shelve provides a simple model for storing objects on files. The operation shelve.open(filename) returns a ``shelf'', which is a simple persistent database with a dictionary-like interface. Database keys are strings, objects stored in the database can be anything that pickle will handle.



guido@cwi.nl