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