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