Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 1 | \section{\module{pickle} --- Python object serialization} |
Fred Drake | b91e934 | 1998-07-23 17:59:49 +0000 | [diff] [blame] | 2 | |
Fred Drake | ffbe687 | 1999-04-22 21:23:22 +0000 | [diff] [blame] | 3 | \declaremodule{standard}{pickle} |
Fred Drake | b91e934 | 1998-07-23 17:59:49 +0000 | [diff] [blame] | 4 | \modulesynopsis{Convert Python objects to streams of bytes and back.} |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 5 | % Substantial improvements by Jim Kerr <jbkerr@sr.hp.com>. |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 6 | % Rewritten by Barry Warsaw <barry@zope.com> |
Fred Drake | b91e934 | 1998-07-23 17:59:49 +0000 | [diff] [blame] | 7 | |
Thomas Wouters | f831663 | 2000-07-16 19:01:10 +0000 | [diff] [blame] | 8 | \index{persistence} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 9 | \indexii{persistent}{objects} |
| 10 | \indexii{serializing}{objects} |
| 11 | \indexii{marshalling}{objects} |
| 12 | \indexii{flattening}{objects} |
| 13 | \indexii{pickling}{objects} |
| 14 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 15 | The \module{pickle} module implements a fundamental, but powerful |
| 16 | algorithm for serializing and de-serializing a Python object |
| 17 | structure. ``Pickling'' is the process whereby a Python object |
| 18 | hierarchy is converted into a byte stream, and ``unpickling'' is the |
| 19 | inverse operation, whereby a byte stream is converted back into an |
| 20 | object hierarchy. Pickling (and unpickling) is alternatively known as |
Fred Drake | 2744f43 | 2001-11-26 21:30:36 +0000 | [diff] [blame] | 21 | ``serialization'', ``marshalling,''\footnote{Don't confuse this with |
| 22 | the \refmodule{marshal} module} or ``flattening'', |
Raymond Hettinger | 35fd926 | 2003-06-25 15:07:45 +0000 | [diff] [blame] | 23 | however, to avoid confusion, the terms used here are ``pickling'' and |
| 24 | ``unpickling''. |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 25 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 26 | This documentation describes both the \module{pickle} module and the |
Fred Drake | 2744f43 | 2001-11-26 21:30:36 +0000 | [diff] [blame] | 27 | \refmodule{cPickle} module. |
Fred Drake | ffbe687 | 1999-04-22 21:23:22 +0000 | [diff] [blame] | 28 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 29 | \subsection{Relationship to other Python modules} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 30 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 31 | The \module{pickle} module has an optimized cousin called the |
| 32 | \module{cPickle} module. As its name implies, \module{cPickle} is |
| 33 | written in C, so it can be up to 1000 times faster than |
| 34 | \module{pickle}. However it does not support subclassing of the |
| 35 | \function{Pickler()} and \function{Unpickler()} classes, because in |
| 36 | \module{cPickle} these are functions, not classes. Most applications |
| 37 | have no need for this functionality, and can benefit from the improved |
| 38 | performance of \module{cPickle}. Other than that, the interfaces of |
| 39 | the two modules are nearly identical; the common interface is |
| 40 | described in this manual and differences are pointed out where |
| 41 | necessary. In the following discussions, we use the term ``pickle'' |
| 42 | to collectively describe the \module{pickle} and |
| 43 | \module{cPickle} modules. |
Guido van Rossum | 736fe5e | 1997-12-09 20:45:08 +0000 | [diff] [blame] | 44 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 45 | The data streams the two modules produce are guaranteed to be |
| 46 | interchangeable. |
| 47 | |
| 48 | Python has a more primitive serialization module called |
Fred Drake | 2744f43 | 2001-11-26 21:30:36 +0000 | [diff] [blame] | 49 | \refmodule{marshal}, but in general |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 50 | \module{pickle} should always be the preferred way to serialize Python |
| 51 | objects. \module{marshal} exists primarily to support Python's |
| 52 | \file{.pyc} files. |
| 53 | |
| 54 | The \module{pickle} module differs from \refmodule{marshal} several |
| 55 | significant ways: |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 56 | |
| 57 | \begin{itemize} |
| 58 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 59 | \item The \module{pickle} module keeps track of the objects it has |
| 60 | already serialized, so that later references to the same object |
| 61 | won't be serialized again. \module{marshal} doesn't do this. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 62 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 63 | This has implications both for recursive objects and object |
| 64 | sharing. Recursive objects are objects that contain references |
| 65 | to themselves. These are not handled by marshal, and in fact, |
| 66 | attempting to marshal recursive objects will crash your Python |
| 67 | interpreter. Object sharing happens when there are multiple |
| 68 | references to the same object in different places in the object |
| 69 | hierarchy being serialized. \module{pickle} stores such objects |
| 70 | only once, and ensures that all other references point to the |
| 71 | master copy. Shared objects remain shared, which can be very |
| 72 | important for mutable objects. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 73 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 74 | \item \module{marshal} cannot be used to serialize user-defined |
| 75 | classes and their instances. \module{pickle} can save and |
| 76 | restore class instances transparently, however the class |
| 77 | definition must be importable and live in the same module as |
| 78 | when the object was stored. |
| 79 | |
| 80 | \item The \module{marshal} serialization format is not guaranteed to |
| 81 | be portable across Python versions. Because its primary job in |
| 82 | life is to support \file{.pyc} files, the Python implementers |
| 83 | reserve the right to change the serialization format in |
| 84 | non-backwards compatible ways should the need arise. The |
| 85 | \module{pickle} serialization format is guaranteed to be |
| 86 | backwards compatible across Python releases. |
| 87 | |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 88 | \end{itemize} |
| 89 | |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 90 | \begin{notice}[warning] |
| 91 | The \module{pickle} module is not intended to be secure against |
| 92 | erroneous or maliciously constructed data. Never unpickle data |
| 93 | received from an untrusted or unauthenticated source. |
| 94 | \end{notice} |
| 95 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 96 | Note that serialization is a more primitive notion than persistence; |
| 97 | although |
| 98 | \module{pickle} reads and writes file objects, it does not handle the |
| 99 | issue of naming persistent objects, nor the (even more complicated) |
| 100 | issue of concurrent access to persistent objects. The \module{pickle} |
| 101 | module can transform a complex object into a byte stream and it can |
| 102 | transform the byte stream into an object with the same internal |
| 103 | structure. Perhaps the most obvious thing to do with these byte |
| 104 | streams is to write them onto a file, but it is also conceivable to |
| 105 | send them across a network or store them in a database. The module |
| 106 | \refmodule{shelve} provides a simple interface |
| 107 | to pickle and unpickle objects on DBM-style database files. |
| 108 | |
| 109 | \subsection{Data stream format} |
| 110 | |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 111 | The data format used by \module{pickle} is Python-specific. This has |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 112 | the advantage that there are no restrictions imposed by external |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 113 | standards such as XDR\index{XDR}\index{External Data Representation} |
| 114 | (which can't represent pointer sharing); however it means that |
| 115 | non-Python programs may not be able to reconstruct pickled Python |
| 116 | objects. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 117 | |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 118 | By default, the \module{pickle} data format uses a printable \ASCII{} |
Guido van Rossum | 736fe5e | 1997-12-09 20:45:08 +0000 | [diff] [blame] | 119 | representation. This is slightly more voluminous than a binary |
| 120 | representation. The big advantage of using printable \ASCII{} (and of |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 121 | some other characteristics of \module{pickle}'s representation) is that |
Guido van Rossum | 736fe5e | 1997-12-09 20:45:08 +0000 | [diff] [blame] | 122 | for debugging or recovery purposes it is possible for a human to read |
| 123 | the pickled file with a standard text editor. |
| 124 | |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 125 | There are currently 3 different protocols which can be used for pickling. |
| 126 | |
| 127 | \begin{itemize} |
| 128 | |
| 129 | \item Protocol version 0 is the original ASCII protocol and is backwards |
| 130 | compatible with earlier versions of Python. |
| 131 | |
| 132 | \item Protocol version 1 is the old binary format which is also compatible |
| 133 | with earlier versions of Python. |
| 134 | |
| 135 | \item Protocol version 2 was introduced in Python 2.3. It provides |
| 136 | much more efficient pickling of new-style classes. |
| 137 | |
| 138 | \end{itemize} |
| 139 | |
| 140 | Refer to PEP 307 for more information. |
| 141 | |
| 142 | If a \var{protocol} is not specified, protocol 0 is used. |
Neal Norwitz | d08baa9 | 2003-02-21 00:26:33 +0000 | [diff] [blame] | 143 | If \var{protocol} is specified as a negative value |
| 144 | or \constant{HIGHEST_PROTOCOL}, |
| 145 | the highest protocol version available will be used. |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 146 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 147 | \versionchanged[Introduced the \var{protocol} parameter]{2.3} |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 148 | |
Guido van Rossum | 736fe5e | 1997-12-09 20:45:08 +0000 | [diff] [blame] | 149 | A binary format, which is slightly more efficient, can be chosen by |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 150 | specifying a \var{protocol} version >= 1. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 151 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 152 | \subsection{Usage} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 153 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 154 | To serialize an object hierarchy, you first create a pickler, then you |
| 155 | call the pickler's \method{dump()} method. To de-serialize a data |
| 156 | stream, you first create an unpickler, then you call the unpickler's |
| 157 | \method{load()} method. The \module{pickle} module provides the |
Neal Norwitz | d08baa9 | 2003-02-21 00:26:33 +0000 | [diff] [blame] | 158 | following constant: |
| 159 | |
| 160 | \begin{datadesc}{HIGHEST_PROTOCOL} |
| 161 | The highest protocol version available. This value can be passed |
| 162 | as a \var{protocol} value. |
Fred Drake | 7c4d8f3 | 2003-09-10 20:47:43 +0000 | [diff] [blame] | 163 | \versionadded{2.3} |
Neal Norwitz | d08baa9 | 2003-02-21 00:26:33 +0000 | [diff] [blame] | 164 | \end{datadesc} |
| 165 | |
| 166 | The \module{pickle} module provides the |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 167 | following functions to make this process more convenient: |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 168 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 169 | \begin{funcdesc}{dump}{obj, file\optional{, protocol}} |
Andrew M. Kuchling | 2ee6a70 | 2004-08-07 20:25:55 +0000 | [diff] [blame] | 170 | Write a pickled representation of \var{obj} to the open file object |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 171 | \var{file}. This is equivalent to |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 172 | \code{Pickler(\var{file}, \var{protocol}).dump(\var{obj})}. |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 173 | |
Andrew M. Kuchling | 2ee6a70 | 2004-08-07 20:25:55 +0000 | [diff] [blame] | 174 | If the \var{protocol} parameter is omitted, protocol 0 is used. |
Neal Norwitz | d08baa9 | 2003-02-21 00:26:33 +0000 | [diff] [blame] | 175 | If \var{protocol} is specified as a negative value |
| 176 | or \constant{HIGHEST_PROTOCOL}, |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 177 | the highest protocol version will be used. |
| 178 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 179 | \versionchanged[Introduced the \var{protocol} parameter]{2.3} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 180 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 181 | \var{file} must have a \method{write()} method that accepts a single |
| 182 | string argument. It can thus be a file object opened for writing, a |
| 183 | \refmodule{StringIO} object, or any other custom |
| 184 | object that meets this interface. |
| 185 | \end{funcdesc} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 186 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 187 | \begin{funcdesc}{load}{file} |
| 188 | Read a string from the open file object \var{file} and interpret it as |
| 189 | a pickle data stream, reconstructing and returning the original object |
| 190 | hierarchy. This is equivalent to \code{Unpickler(\var{file}).load()}. |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 191 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 192 | \var{file} must have two methods, a \method{read()} method that takes |
| 193 | an integer argument, and a \method{readline()} method that requires no |
| 194 | arguments. Both methods should return a string. Thus \var{file} can |
| 195 | be a file object opened for reading, a |
| 196 | \module{StringIO} object, or any other custom |
| 197 | object that meets this interface. |
Guido van Rossum | 736fe5e | 1997-12-09 20:45:08 +0000 | [diff] [blame] | 198 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 199 | This function automatically determines whether the data stream was |
| 200 | written in binary mode or not. |
| 201 | \end{funcdesc} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 202 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 203 | \begin{funcdesc}{dumps}{obj\optional{, protocol}} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 204 | Return the pickled representation of the object as a string, instead |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 205 | of writing it to a file. |
| 206 | |
Andrew M. Kuchling | 2ee6a70 | 2004-08-07 20:25:55 +0000 | [diff] [blame] | 207 | If the \var{protocol} parameter is omitted, protocol 0 is used. |
Neal Norwitz | d08baa9 | 2003-02-21 00:26:33 +0000 | [diff] [blame] | 208 | If \var{protocol} is specified as a negative value |
| 209 | or \constant{HIGHEST_PROTOCOL}, |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 210 | the highest protocol version will be used. |
| 211 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 212 | \versionchanged[The \var{protocol} parameter was added]{2.3} |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 213 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 214 | \end{funcdesc} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 215 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 216 | \begin{funcdesc}{loads}{string} |
| 217 | Read a pickled object hierarchy from a string. Characters in the |
| 218 | string past the pickled object's representation are ignored. |
| 219 | \end{funcdesc} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 220 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 221 | The \module{pickle} module also defines three exceptions: |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 222 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 223 | \begin{excdesc}{PickleError} |
| 224 | A common base class for the other exceptions defined below. This |
| 225 | inherits from \exception{Exception}. |
| 226 | \end{excdesc} |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 227 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 228 | \begin{excdesc}{PicklingError} |
| 229 | This exception is raised when an unpicklable object is passed to |
| 230 | the \method{dump()} method. |
| 231 | \end{excdesc} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 232 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 233 | \begin{excdesc}{UnpicklingError} |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 234 | This exception is raised when there is a problem unpickling an object. |
| 235 | Note that other exceptions may also be raised during unpickling, |
| 236 | including (but not necessarily limited to) \exception{AttributeError}, |
| 237 | \exception{EOFError}, \exception{ImportError}, and \exception{IndexError}. |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 238 | \end{excdesc} |
| 239 | |
| 240 | The \module{pickle} module also exports two callables\footnote{In the |
| 241 | \module{pickle} module these callables are classes, which you could |
Fred Drake | 7c4d8f3 | 2003-09-10 20:47:43 +0000 | [diff] [blame] | 242 | subclass to customize the behavior. However, in the \refmodule{cPickle} |
| 243 | module these callables are factory functions and so cannot be |
| 244 | subclassed. One common reason to subclass is to control what |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 245 | objects can actually be unpickled. See section~\ref{pickle-sub} for |
Fred Drake | 7c4d8f3 | 2003-09-10 20:47:43 +0000 | [diff] [blame] | 246 | more details.}, \class{Pickler} and \class{Unpickler}: |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 247 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 248 | \begin{classdesc}{Pickler}{file\optional{, protocol}} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 249 | This takes a file-like object to which it will write a pickle data |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 250 | stream. |
| 251 | |
Andrew M. Kuchling | 2ee6a70 | 2004-08-07 20:25:55 +0000 | [diff] [blame] | 252 | If the \var{protocol} parameter is omitted, protocol 0 is used. |
Neal Norwitz | 12d31e2 | 2003-02-13 03:12:48 +0000 | [diff] [blame] | 253 | If \var{protocol} is specified as a negative value, |
| 254 | the highest protocol version will be used. |
| 255 | |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 256 | \versionchanged[Introduced the \var{protocol} parameter]{2.3} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 257 | |
| 258 | \var{file} must have a \method{write()} method that accepts a single |
| 259 | string argument. It can thus be an open file object, a |
| 260 | \module{StringIO} object, or any other custom |
| 261 | object that meets this interface. |
| 262 | \end{classdesc} |
| 263 | |
| 264 | \class{Pickler} objects define one (or two) public methods: |
| 265 | |
Andrew M. Kuchling | 2ee6a70 | 2004-08-07 20:25:55 +0000 | [diff] [blame] | 266 | \begin{methoddesc}[Pickler]{dump}{obj} |
| 267 | Write a pickled representation of \var{obj} to the open file object |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 268 | given in the constructor. Either the binary or \ASCII{} format will |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 269 | be used, depending on the value of the \var{protocol} argument passed to the |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 270 | constructor. |
| 271 | \end{methoddesc} |
| 272 | |
| 273 | \begin{methoddesc}[Pickler]{clear_memo}{} |
| 274 | Clears the pickler's ``memo''. The memo is the data structure that |
| 275 | remembers which objects the pickler has already seen, so that shared |
| 276 | or recursive objects pickled by reference and not by value. This |
| 277 | method is useful when re-using picklers. |
| 278 | |
Fred Drake | 7f781c9 | 2002-05-01 20:33:53 +0000 | [diff] [blame] | 279 | \begin{notice} |
| 280 | Prior to Python 2.3, \method{clear_memo()} was only available on the |
| 281 | picklers created by \refmodule{cPickle}. In the \module{pickle} module, |
| 282 | picklers have an instance variable called \member{memo} which is a |
| 283 | Python dictionary. So to clear the memo for a \module{pickle} module |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 284 | pickler, you could do the following: |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 285 | |
Fred Drake | 1947991 | 1998-02-13 06:58:54 +0000 | [diff] [blame] | 286 | \begin{verbatim} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 287 | mypickler.memo.clear() |
Fred Drake | 1947991 | 1998-02-13 06:58:54 +0000 | [diff] [blame] | 288 | \end{verbatim} |
Fred Drake | 7f781c9 | 2002-05-01 20:33:53 +0000 | [diff] [blame] | 289 | |
| 290 | Code that does not need to support older versions of Python should |
| 291 | simply use \method{clear_memo()}. |
| 292 | \end{notice} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 293 | \end{methoddesc} |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 294 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 295 | It is possible to make multiple calls to the \method{dump()} method of |
| 296 | the same \class{Pickler} instance. These must then be matched to the |
| 297 | same number of calls to the \method{load()} method of the |
| 298 | corresponding \class{Unpickler} instance. If the same object is |
| 299 | pickled by multiple \method{dump()} calls, the \method{load()} will |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 300 | all yield references to the same object.\footnote{\emph{Warning}: this |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 301 | is intended for pickling multiple objects without intervening |
| 302 | modifications to the objects or their parts. If you modify an object |
| 303 | and then pickle it again using the same \class{Pickler} instance, the |
| 304 | object is not pickled again --- a reference to it is pickled and the |
| 305 | \class{Unpickler} will return the old value, not the modified one. |
| 306 | There are two problems here: (1) detecting changes, and (2) |
| 307 | marshalling a minimal set of changes. Garbage Collection may also |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 308 | become a problem here.} |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 309 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 310 | \class{Unpickler} objects are defined as: |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 311 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 312 | \begin{classdesc}{Unpickler}{file} |
| 313 | This takes a file-like object from which it will read a pickle data |
| 314 | stream. This class automatically determines whether the data stream |
| 315 | was written in binary mode or not, so it does not need a flag as in |
| 316 | the \class{Pickler} factory. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 317 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 318 | \var{file} must have two methods, a \method{read()} method that takes |
| 319 | an integer argument, and a \method{readline()} method that requires no |
| 320 | arguments. Both methods should return a string. Thus \var{file} can |
| 321 | be a file object opened for reading, a |
| 322 | \module{StringIO} object, or any other custom |
| 323 | object that meets this interface. |
| 324 | \end{classdesc} |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 325 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 326 | \class{Unpickler} objects have one (or two) public methods: |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 327 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 328 | \begin{methoddesc}[Unpickler]{load}{} |
| 329 | Read a pickled object representation from the open file object given |
| 330 | in the constructor, and return the reconstituted object hierarchy |
| 331 | specified therein. |
| 332 | \end{methoddesc} |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 333 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 334 | \begin{methoddesc}[Unpickler]{noload}{} |
| 335 | This is just like \method{load()} except that it doesn't actually |
| 336 | create any objects. This is useful primarily for finding what's |
| 337 | called ``persistent ids'' that may be referenced in a pickle data |
| 338 | stream. See section~\ref{pickle-protocol} below for more details. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 339 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 340 | \strong{Note:} the \method{noload()} method is currently only |
| 341 | available on \class{Unpickler} objects created with the |
| 342 | \module{cPickle} module. \module{pickle} module \class{Unpickler}s do |
| 343 | not have the \method{noload()} method. |
| 344 | \end{methoddesc} |
| 345 | |
| 346 | \subsection{What can be pickled and unpickled?} |
Guido van Rossum | 736fe5e | 1997-12-09 20:45:08 +0000 | [diff] [blame] | 347 | |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 348 | The following types can be pickled: |
Fred Drake | 4179691 | 1999-07-02 14:25:37 +0000 | [diff] [blame] | 349 | |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 350 | \begin{itemize} |
| 351 | |
Raymond Hettinger | acb45d7 | 2002-08-05 03:55:36 +0000 | [diff] [blame] | 352 | \item \code{None}, \code{True}, and \code{False} |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 353 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 354 | \item integers, long integers, floating point numbers, complex numbers |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 355 | |
Fred Drake | 56ced2a | 2000-04-06 15:04:30 +0000 | [diff] [blame] | 356 | \item normal and Unicode strings |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 357 | |
Raymond Hettinger | 621c53e | 2004-01-01 05:53:51 +0000 | [diff] [blame] | 358 | \item tuples, lists, sets, and dictionaries containing only picklable objects |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 359 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 360 | \item functions defined at the top level of a module |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 361 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 362 | \item built-in functions defined at the top level of a module |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 363 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 364 | \item classes that are defined at the top level of a module |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 365 | |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 366 | \item instances of such classes whose \member{__dict__} or |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 367 | \method{__setstate__()} is picklable (see |
| 368 | section~\ref{pickle-protocol} for details) |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 369 | |
| 370 | \end{itemize} |
| 371 | |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 372 | Attempts to pickle unpicklable objects will raise the |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 373 | \exception{PicklingError} exception; when this happens, an unspecified |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 374 | number of bytes may have already been written to the underlying file. |
Guido van Rossum | d188358 | 1995-02-15 15:53:08 +0000 | [diff] [blame] | 375 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 376 | Note that functions (built-in and user-defined) are pickled by ``fully |
| 377 | qualified'' name reference, not by value. This means that only the |
| 378 | function name is pickled, along with the name of module the function |
| 379 | is defined in. Neither the function's code, nor any of its function |
| 380 | attributes are pickled. Thus the defining module must be importable |
| 381 | in the unpickling environment, and the module must contain the named |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 382 | object, otherwise an exception will be raised.\footnote{The exception |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 383 | raised will likely be an \exception{ImportError} or an |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 384 | \exception{AttributeError} but it could be something else.} |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 385 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 386 | Similarly, classes are pickled by named reference, so the same |
| 387 | restrictions in the unpickling environment apply. Note that none of |
| 388 | the class's code or data is pickled, so in the following example the |
| 389 | class attribute \code{attr} is not restored in the unpickling |
| 390 | environment: |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 391 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 392 | \begin{verbatim} |
| 393 | class Foo: |
| 394 | attr = 'a class attr' |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 395 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 396 | picklestring = pickle.dumps(Foo) |
| 397 | \end{verbatim} |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 398 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 399 | These restrictions are why picklable functions and classes must be |
| 400 | defined in the top level of a module. |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 401 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 402 | Similarly, when class instances are pickled, their class's code and |
| 403 | data are not pickled along with them. Only the instance data are |
| 404 | pickled. This is done on purpose, so you can fix bugs in a class or |
| 405 | add methods to the class and still load objects that were created with |
| 406 | an earlier version of the class. If you plan to have long-lived |
| 407 | objects that will see many versions of a class, it may be worthwhile |
| 408 | to put a version number in the objects so that suitable conversions |
| 409 | can be made by the class's \method{__setstate__()} method. |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 410 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 411 | \subsection{The pickle protocol |
| 412 | \label{pickle-protocol}}\setindexsubitem{(pickle protocol)} |
Fred Drake | 4074896 | 1998-03-06 21:27:14 +0000 | [diff] [blame] | 413 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 414 | This section describes the ``pickling protocol'' that defines the |
| 415 | interface between the pickler/unpickler and the objects that are being |
| 416 | serialized. This protocol provides a standard way for you to define, |
| 417 | customize, and control how your objects are serialized and |
| 418 | de-serialized. The description in this section doesn't cover specific |
| 419 | customizations that you can employ to make the unpickling environment |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 420 | slightly safer from untrusted pickle data streams; see section~\ref{pickle-sub} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 421 | for more details. |
Fred Drake | 4074896 | 1998-03-06 21:27:14 +0000 | [diff] [blame] | 422 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 423 | \subsubsection{Pickling and unpickling normal class |
| 424 | instances\label{pickle-inst}} |
Fred Drake | 9b28fe2 | 1998-04-04 06:20:28 +0000 | [diff] [blame] | 425 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 426 | When a pickled class instance is unpickled, its \method{__init__()} |
| 427 | method is normally \emph{not} invoked. If it is desirable that the |
Fred Drake | 0de77d1 | 2004-05-05 04:54:37 +0000 | [diff] [blame] | 428 | \method{__init__()} method be called on unpickling, an old-style class |
| 429 | can define a method \method{__getinitargs__()}, which should return a |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 430 | \emph{tuple} containing the arguments to be passed to the class |
Raymond Hettinger | 3489cad | 2004-12-05 05:20:42 +0000 | [diff] [blame] | 431 | constructor (\method{__init__()} for example). The |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 432 | \method{__getinitargs__()} method is called at |
| 433 | pickle time; the tuple it returns is incorporated in the pickle for |
| 434 | the instance. |
| 435 | \withsubitem{(copy protocol)}{\ttindex{__getinitargs__()}} |
| 436 | \withsubitem{(instance constructor)}{\ttindex{__init__()}} |
Fred Drake | 17e5640 | 1998-04-11 20:43:51 +0000 | [diff] [blame] | 437 | |
Fred Drake | 8aa8c84 | 2004-05-05 04:56:06 +0000 | [diff] [blame] | 438 | \withsubitem{(copy protocol)}{\ttindex{__getnewargs__()}} |
| 439 | |
Fred Drake | 0de77d1 | 2004-05-05 04:54:37 +0000 | [diff] [blame] | 440 | New-style types can provide a \method{__getnewargs__()} method that is |
| 441 | used for protocol 2. Implementing this method is needed if the type |
| 442 | establishes some internal invariants when the instance is created, or |
| 443 | if the memory allocation is affected by the values passed to the |
| 444 | \method{__new__()} method for the type (as it is for tuples and |
| 445 | strings). Instances of a new-style type \class{C} are created using |
| 446 | |
| 447 | \begin{alltt} |
| 448 | obj = C.__new__(C, *\var{args}) |
| 449 | \end{alltt} |
| 450 | |
| 451 | where \var{args} is the result of calling \method{__getnewargs__()} on |
| 452 | the original object; if there is no \method{__getnewargs__()}, an |
| 453 | empty tuple is assumed. |
| 454 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 455 | \withsubitem{(copy protocol)}{ |
| 456 | \ttindex{__getstate__()}\ttindex{__setstate__()}} |
| 457 | \withsubitem{(instance attribute)}{ |
| 458 | \ttindex{__dict__}} |
Fred Drake | 17e5640 | 1998-04-11 20:43:51 +0000 | [diff] [blame] | 459 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 460 | Classes can further influence how their instances are pickled; if the |
| 461 | class defines the method \method{__getstate__()}, it is called and the |
| 462 | return state is pickled as the contents for the instance, instead of |
| 463 | the contents of the instance's dictionary. If there is no |
| 464 | \method{__getstate__()} method, the instance's \member{__dict__} is |
| 465 | pickled. |
Fred Drake | 9463de2 | 1998-04-11 20:05:43 +0000 | [diff] [blame] | 466 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 467 | Upon unpickling, if the class also defines the method |
| 468 | \method{__setstate__()}, it is called with the unpickled |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 469 | state.\footnote{These methods can also be used to implement copying |
| 470 | class instances.} If there is no \method{__setstate__()} method, the |
Fred Drake | e9cfcef | 2002-11-27 05:26:46 +0000 | [diff] [blame] | 471 | pickled state must be a dictionary and its items are assigned to the |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 472 | new instance's dictionary. If a class defines both |
| 473 | \method{__getstate__()} and \method{__setstate__()}, the state object |
| 474 | needn't be a dictionary and these methods can do what they |
Fred Drake | e9cfcef | 2002-11-27 05:26:46 +0000 | [diff] [blame] | 475 | want.\footnote{This protocol is also used by the shallow and deep |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 476 | copying operations defined in the |
Fred Drake | e9cfcef | 2002-11-27 05:26:46 +0000 | [diff] [blame] | 477 | \refmodule{copy} module.} |
| 478 | |
| 479 | \begin{notice}[warning] |
| 480 | For new-style classes, if \method{__getstate__()} returns a false |
| 481 | value, the \method{__setstate__()} method will not be called. |
| 482 | \end{notice} |
| 483 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 484 | |
| 485 | \subsubsection{Pickling and unpickling extension types} |
| 486 | |
| 487 | When the \class{Pickler} encounters an object of a type it knows |
| 488 | nothing about --- such as an extension type --- it looks in two places |
| 489 | for a hint of how to pickle it. One alternative is for the object to |
| 490 | implement a \method{__reduce__()} method. If provided, at pickling |
| 491 | time \method{__reduce__()} will be called with no arguments, and it |
| 492 | must return either a string or a tuple. |
| 493 | |
| 494 | If a string is returned, it names a global variable whose contents are |
Andrew M. Kuchling | cbbee6f | 2004-08-07 16:24:18 +0000 | [diff] [blame] | 495 | pickled as normal. The string returned by \method{__reduce__} should |
| 496 | be the object's local name relative to its module; the pickle module |
| 497 | searches the module namespace to determine the object's module. |
| 498 | |
| 499 | When a tuple is returned, it must be between two and five elements |
| 500 | long. Optional elements can either be omitted, or \code{None} can be provided |
| 501 | as their value. The semantics of each element are: |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 502 | |
| 503 | \begin{itemize} |
| 504 | |
Andrew M. Kuchling | cbbee6f | 2004-08-07 16:24:18 +0000 | [diff] [blame] | 505 | \item A callable object that will be called to create the initial |
| 506 | version of the object. The next element of the tuple will provide |
| 507 | arguments for this callable, and later elements provide additional |
| 508 | state information that will subsequently be used to fully reconstruct |
| 509 | the pickled date. |
| 510 | |
| 511 | In the unpickling environment this object must be either a class, a |
| 512 | callable registered as a ``safe constructor'' (see below), or it must |
| 513 | have an attribute \member{__safe_for_unpickling__} with a true value. |
| 514 | Otherwise, an \exception{UnpicklingError} will be raised in the |
| 515 | unpickling environment. Note that as usual, the callable itself is |
| 516 | pickled by name. |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 517 | |
Raymond Hettinger | a6b45cc | 2004-12-07 07:05:57 +0000 | [diff] [blame^] | 518 | \item A tuple of arguments for the callable object. |
| 519 | \versionchanged[Formerly, this argument could also be \code{None}]{2.5} |
Andrew M. Kuchling | cbbee6f | 2004-08-07 16:24:18 +0000 | [diff] [blame] | 520 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 521 | \item Optionally, the object's state, which will be passed to |
| 522 | the object's \method{__setstate__()} method as described in |
| 523 | section~\ref{pickle-inst}. If the object has no |
| 524 | \method{__setstate__()} method, then, as above, the value must |
| 525 | be a dictionary and it will be added to the object's |
| 526 | \member{__dict__}. |
| 527 | |
Andrew M. Kuchling | 14d535c | 2004-08-07 15:49:24 +0000 | [diff] [blame] | 528 | \item Optionally, an iterator (and not a sequence) yielding successive |
| 529 | list items. These list items will be pickled, and appended to the |
| 530 | object using either \code{obj.append(\var{item})} or |
| 531 | \code{obj.extend(\var{list_of_items})}. This is primarily used for |
| 532 | list subclasses, but may be used by other classes as long as they have |
| 533 | \method{append()} and \method{extend()} methods with the appropriate |
| 534 | signature. (Whether \method{append()} or \method{extend()} is used |
| 535 | depends on which pickle protocol version is used as well as the number |
| 536 | of items to append, so both must be supported.) |
| 537 | |
| 538 | \item Optionally, an iterator (not a sequence) |
| 539 | yielding successive dictionary items, which should be tuples of the |
| 540 | form \code{(\var{key}, \var{value})}. These items will be pickled |
| 541 | and stored to the object using \code{obj[\var{key}] = \var{value}}. |
| 542 | This is primarily used for dictionary subclasses, but may be used by |
| 543 | other classes as long as they implement \method{__setitem__}. |
| 544 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 545 | \end{itemize} |
| 546 | |
Andrew M. Kuchling | 14d535c | 2004-08-07 15:49:24 +0000 | [diff] [blame] | 547 | It is sometimes useful to know the protocol version when implementing |
| 548 | \method{__reduce__}. This can be done by implementing a method named |
| 549 | \method{__reduce_ex__} instead of \method{__reduce__}. |
| 550 | \method{__reduce_ex__}, when it exists, is called in preference over |
| 551 | \method{__reduce__} (you may still provide \method{__reduce__} for |
| 552 | backwards compatibility). The \method{__reduce_ex__} method will be |
| 553 | called with a single integer argument, the protocol version. |
| 554 | |
| 555 | The \class{object} class implements both \method{__reduce__} and |
| 556 | \method{__reduce_ex__}; however, if a subclass overrides |
| 557 | \method{__reduce__} but not \method{__reduce_ex__}, the |
| 558 | \method{__reduce_ex__} implementation detects this and calls |
| 559 | \method{__reduce__}. |
| 560 | |
Andrew M. Kuchling | cbbee6f | 2004-08-07 16:24:18 +0000 | [diff] [blame] | 561 | An alternative to implementing a \method{__reduce__()} method on the |
| 562 | object to be pickled, is to register the callable with the |
| 563 | \refmodule[copyreg]{copy_reg} module. This module provides a way |
| 564 | for programs to register ``reduction functions'' and constructors for |
| 565 | user-defined types. Reduction functions have the same semantics and |
| 566 | interface as the \method{__reduce__()} method described above, except |
| 567 | that they are called with a single argument, the object to be pickled. |
| 568 | |
| 569 | The registered constructor is deemed a ``safe constructor'' for purposes |
| 570 | of unpickling as described above. |
Andrew M. Kuchling | 14d535c | 2004-08-07 15:49:24 +0000 | [diff] [blame] | 571 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 572 | |
| 573 | \subsubsection{Pickling and unpickling external objects} |
| 574 | |
| 575 | For the benefit of object persistence, the \module{pickle} module |
| 576 | supports the notion of a reference to an object outside the pickled |
| 577 | data stream. Such objects are referenced by a ``persistent id'', |
| 578 | which is just an arbitrary string of printable \ASCII{} characters. |
| 579 | The resolution of such names is not defined by the \module{pickle} |
| 580 | module; it will delegate this resolution to user defined functions on |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 581 | the pickler and unpickler.\footnote{The actual mechanism for |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 582 | associating these user defined functions is slightly different for |
| 583 | \module{pickle} and \module{cPickle}. The description given here |
| 584 | works the same for both implementations. Users of the \module{pickle} |
| 585 | module could also use subclassing to effect the same results, |
| 586 | overriding the \method{persistent_id()} and \method{persistent_load()} |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 587 | methods in the derived classes.} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 588 | |
| 589 | To define external persistent id resolution, you need to set the |
| 590 | \member{persistent_id} attribute of the pickler object and the |
| 591 | \member{persistent_load} attribute of the unpickler object. |
| 592 | |
| 593 | To pickle objects that have an external persistent id, the pickler |
| 594 | must have a custom \function{persistent_id()} method that takes an |
| 595 | object as an argument and returns either \code{None} or the persistent |
| 596 | id for that object. When \code{None} is returned, the pickler simply |
| 597 | pickles the object as normal. When a persistent id string is |
| 598 | returned, the pickler will pickle that string, along with a marker |
| 599 | so that the unpickler will recognize the string as a persistent id. |
| 600 | |
| 601 | To unpickle external objects, the unpickler must have a custom |
| 602 | \function{persistent_load()} function that takes a persistent id |
| 603 | string and returns the referenced object. |
| 604 | |
| 605 | Here's a silly example that \emph{might} shed more light: |
| 606 | |
| 607 | \begin{verbatim} |
| 608 | import pickle |
| 609 | from cStringIO import StringIO |
| 610 | |
| 611 | src = StringIO() |
| 612 | p = pickle.Pickler(src) |
| 613 | |
| 614 | def persistent_id(obj): |
| 615 | if hasattr(obj, 'x'): |
| 616 | return 'the value %d' % obj.x |
| 617 | else: |
| 618 | return None |
| 619 | |
| 620 | p.persistent_id = persistent_id |
| 621 | |
| 622 | class Integer: |
| 623 | def __init__(self, x): |
| 624 | self.x = x |
| 625 | def __str__(self): |
| 626 | return 'My name is integer %d' % self.x |
| 627 | |
| 628 | i = Integer(7) |
| 629 | print i |
| 630 | p.dump(i) |
| 631 | |
| 632 | datastream = src.getvalue() |
| 633 | print repr(datastream) |
| 634 | dst = StringIO(datastream) |
| 635 | |
| 636 | up = pickle.Unpickler(dst) |
| 637 | |
| 638 | class FancyInteger(Integer): |
| 639 | def __str__(self): |
| 640 | return 'I am the integer %d' % self.x |
| 641 | |
| 642 | def persistent_load(persid): |
| 643 | if persid.startswith('the value '): |
| 644 | value = int(persid.split()[2]) |
| 645 | return FancyInteger(value) |
| 646 | else: |
| 647 | raise pickle.UnpicklingError, 'Invalid persistent id' |
| 648 | |
| 649 | up.persistent_load = persistent_load |
| 650 | |
| 651 | j = up.load() |
| 652 | print j |
| 653 | \end{verbatim} |
| 654 | |
| 655 | In the \module{cPickle} module, the unpickler's |
| 656 | \member{persistent_load} attribute can also be set to a Python |
| 657 | list, in which case, when the unpickler reaches a persistent id, the |
| 658 | persistent id string will simply be appended to this list. This |
| 659 | functionality exists so that a pickle data stream can be ``sniffed'' |
| 660 | for object references without actually instantiating all the objects |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 661 | in a pickle.\footnote{We'll leave you with the image of Guido and Jim |
| 662 | sitting around sniffing pickles in their living rooms.} Setting |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 663 | \member{persistent_load} to a list is usually used in conjunction with |
| 664 | the \method{noload()} method on the Unpickler. |
| 665 | |
| 666 | % BAW: Both pickle and cPickle support something called |
| 667 | % inst_persistent_id() which appears to give unknown types a second |
| 668 | % shot at producing a persistent id. Since Jim Fulton can't remember |
| 669 | % why it was added or what it's for, I'm leaving it undocumented. |
| 670 | |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 671 | \subsection{Subclassing Unpicklers \label{pickle-sub}} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 672 | |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 673 | By default, unpickling will import any class that it finds in the |
| 674 | pickle data. You can control exactly what gets unpickled and what |
| 675 | gets called by customizing your unpickler. Unfortunately, exactly how |
| 676 | you do this is different depending on whether you're using |
| 677 | \module{pickle} or \module{cPickle}.\footnote{A word of caution: the |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 678 | mechanisms described here use internal attributes and methods, which |
| 679 | are subject to change in future versions of Python. We intend to |
| 680 | someday provide a common interface for controlling this behavior, |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 681 | which will work in either \module{pickle} or \module{cPickle}.} |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 682 | |
| 683 | In the \module{pickle} module, you need to derive a subclass from |
| 684 | \class{Unpickler}, overriding the \method{load_global()} |
| 685 | method. \method{load_global()} should read two lines from the pickle |
Raymond Hettinger | f17d65d | 2003-08-12 00:01:16 +0000 | [diff] [blame] | 686 | data stream where the first line will the name of the module |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 687 | containing the class and the second line will be the name of the |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 688 | instance's class. It then looks up the class, possibly importing the |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 689 | module and digging out the attribute, then it appends what it finds to |
| 690 | the unpickler's stack. Later on, this class will be assigned to the |
| 691 | \member{__class__} attribute of an empty class, as a way of magically |
| 692 | creating an instance without calling its class's \method{__init__()}. |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 693 | Your job (should you choose to accept it), would be to have |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 694 | \method{load_global()} push onto the unpickler's stack, a known safe |
| 695 | version of any class you deem safe to unpickle. It is up to you to |
| 696 | produce such a class. Or you could raise an error if you want to |
| 697 | disallow all unpickling of instances. If this sounds like a hack, |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 698 | you're right. Refer to the source code to make this work. |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 699 | |
| 700 | Things are a little cleaner with \module{cPickle}, but not by much. |
| 701 | To control what gets unpickled, you can set the unpickler's |
| 702 | \member{find_global} attribute to a function or \code{None}. If it is |
| 703 | \code{None} then any attempts to unpickle instances will raise an |
| 704 | \exception{UnpicklingError}. If it is a function, |
| 705 | then it should accept a module name and a class name, and return the |
| 706 | corresponding class object. It is responsible for looking up the |
Andrew M. Kuchling | 7696344 | 2003-05-14 16:51:46 +0000 | [diff] [blame] | 707 | class and performing any necessary imports, and it may raise an |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 708 | error to prevent instances of the class from being unpickled. |
| 709 | |
| 710 | The moral of the story is that you should be really careful about the |
| 711 | source of the strings your application unpickles. |
Fred Drake | 9463de2 | 1998-04-11 20:05:43 +0000 | [diff] [blame] | 712 | |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 713 | \subsection{Example \label{pickle-example}} |
| 714 | |
| 715 | Here's a simple example of how to modify pickling behavior for a |
| 716 | class. The \class{TextReader} class opens a text file, and returns |
| 717 | the line number and line contents each time its \method{readline()} |
| 718 | method is called. If a \class{TextReader} instance is pickled, all |
| 719 | attributes \emph{except} the file object member are saved. When the |
| 720 | instance is unpickled, the file is reopened, and reading resumes from |
| 721 | the last location. The \method{__setstate__()} and |
| 722 | \method{__getstate__()} methods are used to implement this behavior. |
| 723 | |
| 724 | \begin{verbatim} |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 725 | class TextReader: |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 726 | """Print and number lines in a text file.""" |
| 727 | def __init__(self, file): |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 728 | self.file = file |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 729 | self.fh = open(file) |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 730 | self.lineno = 0 |
| 731 | |
| 732 | def readline(self): |
| 733 | self.lineno = self.lineno + 1 |
| 734 | line = self.fh.readline() |
| 735 | if not line: |
| 736 | return None |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 737 | if line.endswith("\n"): |
| 738 | line = line[:-1] |
| 739 | return "%d: %s" % (self.lineno, line) |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 740 | |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 741 | def __getstate__(self): |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 742 | odict = self.__dict__.copy() # copy the dict since we change it |
| 743 | del odict['fh'] # remove filehandle entry |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 744 | return odict |
| 745 | |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 746 | def __setstate__(self,dict): |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 747 | fh = open(dict['file']) # reopen file |
| 748 | count = dict['lineno'] # read from file... |
| 749 | while count: # until line count is restored |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 750 | fh.readline() |
| 751 | count = count - 1 |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 752 | self.__dict__.update(dict) # update attributes |
| 753 | self.fh = fh # save the file object |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 754 | \end{verbatim} |
| 755 | |
| 756 | A sample usage might be something like this: |
| 757 | |
| 758 | \begin{verbatim} |
| 759 | >>> import TextReader |
| 760 | >>> obj = TextReader.TextReader("TextReader.py") |
| 761 | >>> obj.readline() |
| 762 | '1: #!/usr/local/bin/python' |
| 763 | >>> # (more invocations of obj.readline() here) |
| 764 | ... obj.readline() |
| 765 | '7: class TextReader:' |
| 766 | >>> import pickle |
| 767 | >>> pickle.dump(obj,open('save.p','w')) |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 768 | \end{verbatim} |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 769 | |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 770 | If you want to see that \refmodule{pickle} works across Python |
| 771 | processes, start another Python session, before continuing. What |
| 772 | follows can happen from either the same process or a new process. |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 773 | |
Fred Drake | c825280 | 2001-09-25 16:29:17 +0000 | [diff] [blame] | 774 | \begin{verbatim} |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 775 | >>> import pickle |
| 776 | >>> reader = pickle.load(open('save.p')) |
| 777 | >>> reader.readline() |
| 778 | '8: "Print and number lines in a text file."' |
| 779 | \end{verbatim} |
| 780 | |
| 781 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 782 | \begin{seealso} |
| 783 | \seemodule[copyreg]{copy_reg}{Pickle interface constructor |
| 784 | registration for extension types.} |
| 785 | |
| 786 | \seemodule{shelve}{Indexed databases of objects; uses \module{pickle}.} |
| 787 | |
| 788 | \seemodule{copy}{Shallow and deep object copying.} |
| 789 | |
| 790 | \seemodule{marshal}{High-performance serialization of built-in types.} |
| 791 | \end{seealso} |
| 792 | |
| 793 | |
| 794 | \section{\module{cPickle} --- A faster \module{pickle}} |
Fred Drake | ffbe687 | 1999-04-22 21:23:22 +0000 | [diff] [blame] | 795 | |
Fred Drake | b91e934 | 1998-07-23 17:59:49 +0000 | [diff] [blame] | 796 | \declaremodule{builtin}{cPickle} |
Fred Drake | 38e5d27 | 2000-04-03 20:13:55 +0000 | [diff] [blame] | 797 | \modulesynopsis{Faster version of \refmodule{pickle}, but not subclassable.} |
Andrew M. Kuchling | c62af02 | 2004-01-08 15:01:08 +0000 | [diff] [blame] | 798 | \moduleauthor{Jim Fulton}{jim@zope.com} |
Fred Drake | ffbe687 | 1999-04-22 21:23:22 +0000 | [diff] [blame] | 799 | \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} |
Fred Drake | b91e934 | 1998-07-23 17:59:49 +0000 | [diff] [blame] | 800 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 801 | The \module{cPickle} module supports serialization and |
| 802 | de-serialization of Python objects, providing an interface and |
| 803 | functionality nearly identical to the |
| 804 | \refmodule{pickle}\refstmodindex{pickle} module. There are several |
| 805 | differences, the most important being performance and subclassability. |
Fred Drake | 9463de2 | 1998-04-11 20:05:43 +0000 | [diff] [blame] | 806 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 807 | First, \module{cPickle} can be up to 1000 times faster than |
| 808 | \module{pickle} because the former is implemented in C. Second, in |
| 809 | the \module{cPickle} module the callables \function{Pickler()} and |
| 810 | \function{Unpickler()} are functions, not classes. This means that |
| 811 | you cannot use them to derive custom pickling and unpickling |
| 812 | subclasses. Most applications have no need for this functionality and |
| 813 | should benefit from the greatly improved performance of the |
| 814 | \module{cPickle} module. |
Fred Drake | 9463de2 | 1998-04-11 20:05:43 +0000 | [diff] [blame] | 815 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 816 | The pickle data stream produced by \module{pickle} and |
| 817 | \module{cPickle} are identical, so it is possible to use |
| 818 | \module{pickle} and \module{cPickle} interchangeably with existing |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 819 | pickles.\footnote{Since the pickle data format is actually a tiny |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 820 | stack-oriented programming language, and some freedom is taken in the |
| 821 | encodings of certain objects, it is possible that the two modules |
| 822 | produce different data streams for the same input objects. However it |
| 823 | is guaranteed that they will always be able to read each other's |
Fred Drake | f5f0c17 | 2003-09-09 19:49:18 +0000 | [diff] [blame] | 824 | data streams.} |
Guido van Rossum | cf3ce92 | 1999-01-06 23:34:39 +0000 | [diff] [blame] | 825 | |
Barry Warsaw | f595fd9 | 2001-11-15 23:39:07 +0000 | [diff] [blame] | 826 | There are additional minor differences in API between \module{cPickle} |
| 827 | and \module{pickle}, however for most applications, they are |
| 828 | interchangable. More documentation is provided in the |
| 829 | \module{pickle} module documentation, which |
| 830 | includes a list of the documented differences. |
| 831 | |
| 832 | |