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