blob: 194a717fc0a9f7e4ad2b973721f4288371d72859 [file] [log] [blame]
Barry Warsawf595fd92001-11-15 23:39:07 +00001\section{\module{pickle} --- Python object serialization}
Fred Drakeb91e9341998-07-23 17:59:49 +00002
Fred Drakeffbe6871999-04-22 21:23:22 +00003\declaremodule{standard}{pickle}
Fred Drakeb91e9341998-07-23 17:59:49 +00004\modulesynopsis{Convert Python objects to streams of bytes and back.}
Fred Drake38e5d272000-04-03 20:13:55 +00005% Substantial improvements by Jim Kerr <jbkerr@sr.hp.com>.
Barry Warsawf595fd92001-11-15 23:39:07 +00006% Rewritten by Barry Warsaw <barry@zope.com>
Fred Drakeb91e9341998-07-23 17:59:49 +00007
Thomas Woutersf8316632000-07-16 19:01:10 +00008\index{persistence}
Guido van Rossumd1883581995-02-15 15:53:08 +00009\indexii{persistent}{objects}
10\indexii{serializing}{objects}
11\indexii{marshalling}{objects}
12\indexii{flattening}{objects}
13\indexii{pickling}{objects}
14
Barry Warsawf595fd92001-11-15 23:39:07 +000015The \module{pickle} module implements a fundamental, but powerful
16algorithm for serializing and de-serializing a Python object
17structure. ``Pickling'' is the process whereby a Python object
18hierarchy is converted into a byte stream, and ``unpickling'' is the
19inverse operation, whereby a byte stream is converted back into an
20object hierarchy. Pickling (and unpickling) is alternatively known as
Fred Drake2744f432001-11-26 21:30:36 +000021``serialization'', ``marshalling,''\footnote{Don't confuse this with
22the \refmodule{marshal} module} or ``flattening'',
Barry Warsawf595fd92001-11-15 23:39:07 +000023however the preferred term used here is ``pickling'' and
24``unpickling'' to avoid confusing.
Guido van Rossum470be141995-03-17 16:07:09 +000025
Barry Warsawf595fd92001-11-15 23:39:07 +000026This documentation describes both the \module{pickle} module and the
Fred Drake2744f432001-11-26 21:30:36 +000027\refmodule{cPickle} module.
Fred Drakeffbe6871999-04-22 21:23:22 +000028
Barry Warsawf595fd92001-11-15 23:39:07 +000029\subsection{Relationship to other Python modules}
Guido van Rossumd1883581995-02-15 15:53:08 +000030
Barry Warsawf595fd92001-11-15 23:39:07 +000031The \module{pickle} module has an optimized cousin called the
32\module{cPickle} module. As its name implies, \module{cPickle} is
33written 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
37have no need for this functionality, and can benefit from the improved
38performance of \module{cPickle}. Other than that, the interfaces of
39the two modules are nearly identical; the common interface is
40described in this manual and differences are pointed out where
41necessary. In the following discussions, we use the term ``pickle''
42to collectively describe the \module{pickle} and
43\module{cPickle} modules.
Guido van Rossum736fe5e1997-12-09 20:45:08 +000044
Barry Warsawf595fd92001-11-15 23:39:07 +000045The data streams the two modules produce are guaranteed to be
46interchangeable.
47
48Python has a more primitive serialization module called
Fred Drake2744f432001-11-26 21:30:36 +000049\refmodule{marshal}, but in general
Barry Warsawf595fd92001-11-15 23:39:07 +000050\module{pickle} should always be the preferred way to serialize Python
51objects. \module{marshal} exists primarily to support Python's
52\file{.pyc} files.
53
54The \module{pickle} module differs from \refmodule{marshal} several
55significant ways:
Guido van Rossumd1883581995-02-15 15:53:08 +000056
57\begin{itemize}
58
Barry Warsawf595fd92001-11-15 23:39:07 +000059\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 Rossumd1883581995-02-15 15:53:08 +000062
Barry Warsawf595fd92001-11-15 23:39:07 +000063 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 Rossumd1883581995-02-15 15:53:08 +000073
Barry Warsawf595fd92001-11-15 23:39:07 +000074\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 Rossumd1883581995-02-15 15:53:08 +000097
98\end{itemize}
99
Barry Warsawf595fd92001-11-15 23:39:07 +0000100Note that serialization is a more primitive notion than persistence;
101although
102\module{pickle} reads and writes file objects, it does not handle the
103issue of naming persistent objects, nor the (even more complicated)
104issue of concurrent access to persistent objects. The \module{pickle}
105module can transform a complex object into a byte stream and it can
106transform the byte stream into an object with the same internal
107structure. Perhaps the most obvious thing to do with these byte
108streams is to write them onto a file, but it is also conceivable to
109send them across a network or store them in a database. The module
110\refmodule{shelve} provides a simple interface
111to pickle and unpickle objects on DBM-style database files.
112
113\subsection{Data stream format}
114
Fred Drake9b28fe21998-04-04 06:20:28 +0000115The data format used by \module{pickle} is Python-specific. This has
Guido van Rossumd1883581995-02-15 15:53:08 +0000116the advantage that there are no restrictions imposed by external
Barry Warsawf595fd92001-11-15 23:39:07 +0000117standards such as XDR\index{XDR}\index{External Data Representation}
118(which can't represent pointer sharing); however it means that
119non-Python programs may not be able to reconstruct pickled Python
120objects.
Guido van Rossumd1883581995-02-15 15:53:08 +0000121
Fred Drake9b28fe21998-04-04 06:20:28 +0000122By default, the \module{pickle} data format uses a printable \ASCII{}
Guido van Rossum736fe5e1997-12-09 20:45:08 +0000123representation. This is slightly more voluminous than a binary
124representation. The big advantage of using printable \ASCII{} (and of
Fred Drake9b28fe21998-04-04 06:20:28 +0000125some other characteristics of \module{pickle}'s representation) is that
Guido van Rossum736fe5e1997-12-09 20:45:08 +0000126for debugging or recovery purposes it is possible for a human to read
127the pickled file with a standard text editor.
128
129A binary format, which is slightly more efficient, can be chosen by
Barry Warsawf595fd92001-11-15 23:39:07 +0000130specifying a true value for the \var{bin} argument to the
Fred Drake9b28fe21998-04-04 06:20:28 +0000131\class{Pickler} constructor or the \function{dump()} and \function{dumps()}
Barry Warsawf595fd92001-11-15 23:39:07 +0000132functions.
Guido van Rossumd1883581995-02-15 15:53:08 +0000133
Barry Warsawf595fd92001-11-15 23:39:07 +0000134\subsection{Usage}
Guido van Rossumd1883581995-02-15 15:53:08 +0000135
Barry Warsawf595fd92001-11-15 23:39:07 +0000136To serialize an object hierarchy, you first create a pickler, then you
137call the pickler's \method{dump()} method. To de-serialize a data
138stream, you first create an unpickler, then you call the unpickler's
139\method{load()} method. The \module{pickle} module provides the
140following functions to make this process more convenient:
Guido van Rossumd1883581995-02-15 15:53:08 +0000141
Barry Warsawf595fd92001-11-15 23:39:07 +0000142\begin{funcdesc}{dump}{object, file\optional{, bin}}
143Write 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})}.
146If the optional \var{bin} argument is true, the binary pickle format
147is used; otherwise the (less efficient) text pickle format is used
148(for backwards compatibility, this is the default).
Guido van Rossumd1883581995-02-15 15:53:08 +0000149
Barry Warsawf595fd92001-11-15 23:39:07 +0000150\var{file} must have a \method{write()} method that accepts a single
151string argument. It can thus be a file object opened for writing, a
152\refmodule{StringIO} object, or any other custom
153object that meets this interface.
154\end{funcdesc}
Guido van Rossumd1883581995-02-15 15:53:08 +0000155
Barry Warsawf595fd92001-11-15 23:39:07 +0000156\begin{funcdesc}{load}{file}
157Read a string from the open file object \var{file} and interpret it as
158a pickle data stream, reconstructing and returning the original object
159hierarchy. This is equivalent to \code{Unpickler(\var{file}).load()}.
Guido van Rossum470be141995-03-17 16:07:09 +0000160
Barry Warsawf595fd92001-11-15 23:39:07 +0000161\var{file} must have two methods, a \method{read()} method that takes
162an integer argument, and a \method{readline()} method that requires no
163arguments. Both methods should return a string. Thus \var{file} can
164be a file object opened for reading, a
165\module{StringIO} object, or any other custom
166object that meets this interface.
Guido van Rossum736fe5e1997-12-09 20:45:08 +0000167
Barry Warsawf595fd92001-11-15 23:39:07 +0000168This function automatically determines whether the data stream was
169written in binary mode or not.
170\end{funcdesc}
Guido van Rossumd1883581995-02-15 15:53:08 +0000171
Barry Warsawf595fd92001-11-15 23:39:07 +0000172\begin{funcdesc}{dumps}{object\optional{, bin}}
173Return the pickled representation of the object as a string, instead
174of writing it to a file. If the optional \var{bin} argument is
175true, the binary pickle format is used; otherwise the (less efficient)
176text pickle format is used (this is the default).
177\end{funcdesc}
Guido van Rossumd1883581995-02-15 15:53:08 +0000178
Barry Warsawf595fd92001-11-15 23:39:07 +0000179\begin{funcdesc}{loads}{string}
180Read a pickled object hierarchy from a string. Characters in the
181string past the pickled object's representation are ignored.
182\end{funcdesc}
Guido van Rossumd1883581995-02-15 15:53:08 +0000183
Barry Warsawf595fd92001-11-15 23:39:07 +0000184The \module{pickle} module also defines three exceptions:
Guido van Rossum470be141995-03-17 16:07:09 +0000185
Barry Warsawf595fd92001-11-15 23:39:07 +0000186\begin{excdesc}{PickleError}
187A common base class for the other exceptions defined below. This
188inherits from \exception{Exception}.
189\end{excdesc}
Guido van Rossum470be141995-03-17 16:07:09 +0000190
Barry Warsawf595fd92001-11-15 23:39:07 +0000191\begin{excdesc}{PicklingError}
192This exception is raised when an unpicklable object is passed to
193the \method{dump()} method.
194\end{excdesc}
Guido van Rossumd1883581995-02-15 15:53:08 +0000195
Barry Warsawf595fd92001-11-15 23:39:07 +0000196\begin{excdesc}{UnpicklingError}
197This exception is raised when there is a problem unpickling an object,
198such as a security violation. Note that other exceptions may also be
199raised during unpickling, including (but not necessarily limited to)
Neil Schemenauer79f18132002-03-22 22:16:03 +0000200\exception{AttributeError}, \exception{EOFError},
201\exception{ImportError}, and \exception{IndexError}.
Barry Warsawf595fd92001-11-15 23:39:07 +0000202\end{excdesc}
203
204The \module{pickle} module also exports two callables\footnote{In the
205\module{pickle} module these callables are classes, which you could
206subclass to customize the behavior. However, in the \module{cPickle}
207modules these callables are factory functions and so cannot be
208subclassed. One of the common reasons to subclass is to control what
209objects can actually be unpickled. See section~\ref{pickle-sec} for
210more details on security concerns.}, \class{Pickler} and
211\class{Unpickler}:
212
213\begin{classdesc}{Pickler}{file\optional{, bin}}
214This takes a file-like object to which it will write a pickle data
215stream. Optional \var{bin} if true, tells the pickler to use the more
216efficient 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
220string argument. It can thus be an open file object, a
221\module{StringIO} object, or any other custom
222object 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}
228Write a pickled representation of \var{object} to the open file object
229given in the constructor. Either the binary or \ASCII{} format will
230be used, depending on the value of the \var{bin} flag passed to the
231constructor.
232\end{methoddesc}
233
234\begin{methoddesc}[Pickler]{clear_memo}{}
235Clears the pickler's ``memo''. The memo is the data structure that
236remembers which objects the pickler has already seen, so that shared
237or recursive objects pickled by reference and not by value. This
238method is useful when re-using picklers.
239
Fred Drake7f781c92002-05-01 20:33:53 +0000240\begin{notice}
241Prior to Python 2.3, \method{clear_memo()} was only available on the
242picklers created by \refmodule{cPickle}. In the \module{pickle} module,
243picklers have an instance variable called \member{memo} which is a
244Python dictionary. So to clear the memo for a \module{pickle} module
Barry Warsawf595fd92001-11-15 23:39:07 +0000245pickler, you could do the following:
Guido van Rossumd1883581995-02-15 15:53:08 +0000246
Fred Drake19479911998-02-13 06:58:54 +0000247\begin{verbatim}
Barry Warsawf595fd92001-11-15 23:39:07 +0000248mypickler.memo.clear()
Fred Drake19479911998-02-13 06:58:54 +0000249\end{verbatim}
Fred Drake7f781c92002-05-01 20:33:53 +0000250
251Code that does not need to support older versions of Python should
252simply use \method{clear_memo()}.
253\end{notice}
Barry Warsawf595fd92001-11-15 23:39:07 +0000254\end{methoddesc}
Fred Drake9b28fe21998-04-04 06:20:28 +0000255
Barry Warsawf595fd92001-11-15 23:39:07 +0000256It is possible to make multiple calls to the \method{dump()} method of
257the same \class{Pickler} instance. These must then be matched to the
258same number of calls to the \method{load()} method of the
259corresponding \class{Unpickler} instance. If the same object is
260pickled by multiple \method{dump()} calls, the \method{load()} will
261all yield references to the same object\footnote{\emph{Warning}: this
262is intended for pickling multiple objects without intervening
263modifications to the objects or their parts. If you modify an object
264and then pickle it again using the same \class{Pickler} instance, the
265object is not pickled again --- a reference to it is pickled and the
266\class{Unpickler} will return the old value, not the modified one.
267There are two problems here: (1) detecting changes, and (2)
268marshalling a minimal set of changes. Garbage Collection may also
269become a problem here.}.
Guido van Rossum470be141995-03-17 16:07:09 +0000270
Barry Warsawf595fd92001-11-15 23:39:07 +0000271\class{Unpickler} objects are defined as:
Fred Drake9b28fe21998-04-04 06:20:28 +0000272
Barry Warsawf595fd92001-11-15 23:39:07 +0000273\begin{classdesc}{Unpickler}{file}
274This takes a file-like object from which it will read a pickle data
275stream. This class automatically determines whether the data stream
276was written in binary mode or not, so it does not need a flag as in
277the \class{Pickler} factory.
Guido van Rossumd1883581995-02-15 15:53:08 +0000278
Barry Warsawf595fd92001-11-15 23:39:07 +0000279\var{file} must have two methods, a \method{read()} method that takes
280an integer argument, and a \method{readline()} method that requires no
281arguments. Both methods should return a string. Thus \var{file} can
282be a file object opened for reading, a
283\module{StringIO} object, or any other custom
284object that meets this interface.
285\end{classdesc}
Fred Drake9b28fe21998-04-04 06:20:28 +0000286
Barry Warsawf595fd92001-11-15 23:39:07 +0000287\class{Unpickler} objects have one (or two) public methods:
Guido van Rossum470be141995-03-17 16:07:09 +0000288
Barry Warsawf595fd92001-11-15 23:39:07 +0000289\begin{methoddesc}[Unpickler]{load}{}
290Read a pickled object representation from the open file object given
291in the constructor, and return the reconstituted object hierarchy
292specified therein.
293\end{methoddesc}
Fred Drake9b28fe21998-04-04 06:20:28 +0000294
Barry Warsawf595fd92001-11-15 23:39:07 +0000295\begin{methoddesc}[Unpickler]{noload}{}
296This is just like \method{load()} except that it doesn't actually
297create any objects. This is useful primarily for finding what's
298called ``persistent ids'' that may be referenced in a pickle data
299stream. See section~\ref{pickle-protocol} below for more details.
Guido van Rossumd1883581995-02-15 15:53:08 +0000300
Barry Warsawf595fd92001-11-15 23:39:07 +0000301\strong{Note:} the \method{noload()} method is currently only
302available on \class{Unpickler} objects created with the
303\module{cPickle} module. \module{pickle} module \class{Unpickler}s do
304not have the \method{noload()} method.
305\end{methoddesc}
306
307\subsection{What can be pickled and unpickled?}
Guido van Rossum736fe5e1997-12-09 20:45:08 +0000308
Guido van Rossumd1883581995-02-15 15:53:08 +0000309The following types can be pickled:
Fred Drake41796911999-07-02 14:25:37 +0000310
Guido van Rossumd1883581995-02-15 15:53:08 +0000311\begin{itemize}
312
313\item \code{None}
314
Barry Warsawf595fd92001-11-15 23:39:07 +0000315\item integers, long integers, floating point numbers, complex numbers
Guido van Rossumd1883581995-02-15 15:53:08 +0000316
Fred Drake56ced2a2000-04-06 15:04:30 +0000317\item normal and Unicode strings
Guido van Rossumd1883581995-02-15 15:53:08 +0000318
Barry Warsawf595fd92001-11-15 23:39:07 +0000319\item tuples, lists, and dictionaries containing only picklable objects
Guido van Rossumd1883581995-02-15 15:53:08 +0000320
Barry Warsawf595fd92001-11-15 23:39:07 +0000321\item functions defined at the top level of a module
Fred Drake38e5d272000-04-03 20:13:55 +0000322
Barry Warsawf595fd92001-11-15 23:39:07 +0000323\item built-in functions defined at the top level of a module
Fred Drake38e5d272000-04-03 20:13:55 +0000324
Barry Warsawf595fd92001-11-15 23:39:07 +0000325\item classes that are defined at the top level of a module
Guido van Rossum470be141995-03-17 16:07:09 +0000326
Fred Drake9b28fe21998-04-04 06:20:28 +0000327\item instances of such classes whose \member{__dict__} or
Barry Warsawf595fd92001-11-15 23:39:07 +0000328\method{__setstate__()} is picklable (see
329section~\ref{pickle-protocol} for details)
Guido van Rossumd1883581995-02-15 15:53:08 +0000330
331\end{itemize}
332
Guido van Rossum470be141995-03-17 16:07:09 +0000333Attempts to pickle unpicklable objects will raise the
Fred Drake9b28fe21998-04-04 06:20:28 +0000334\exception{PicklingError} exception; when this happens, an unspecified
Barry Warsawf595fd92001-11-15 23:39:07 +0000335number of bytes may have already been written to the underlying file.
Guido van Rossumd1883581995-02-15 15:53:08 +0000336
Barry Warsawf595fd92001-11-15 23:39:07 +0000337Note that functions (built-in and user-defined) are pickled by ``fully
338qualified'' name reference, not by value. This means that only the
339function name is pickled, along with the name of module the function
340is defined in. Neither the function's code, nor any of its function
341attributes are pickled. Thus the defining module must be importable
342in the unpickling environment, and the module must contain the named
343object, otherwise an exception will be raised\footnote{The exception
344raised will likely be an \exception{ImportError} or an
345\exception{AttributeError} but it could be something else.}.
Guido van Rossum470be141995-03-17 16:07:09 +0000346
Barry Warsawf595fd92001-11-15 23:39:07 +0000347Similarly, classes are pickled by named reference, so the same
348restrictions in the unpickling environment apply. Note that none of
349the class's code or data is pickled, so in the following example the
350class attribute \code{attr} is not restored in the unpickling
351environment:
Guido van Rossum470be141995-03-17 16:07:09 +0000352
Barry Warsawf595fd92001-11-15 23:39:07 +0000353\begin{verbatim}
354class Foo:
355 attr = 'a class attr'
Guido van Rossum470be141995-03-17 16:07:09 +0000356
Barry Warsawf595fd92001-11-15 23:39:07 +0000357picklestring = pickle.dumps(Foo)
358\end{verbatim}
Guido van Rossum470be141995-03-17 16:07:09 +0000359
Barry Warsawf595fd92001-11-15 23:39:07 +0000360These restrictions are why picklable functions and classes must be
361defined in the top level of a module.
Guido van Rossum470be141995-03-17 16:07:09 +0000362
Barry Warsawf595fd92001-11-15 23:39:07 +0000363Similarly, when class instances are pickled, their class's code and
364data are not pickled along with them. Only the instance data are
365pickled. This is done on purpose, so you can fix bugs in a class or
366add methods to the class and still load objects that were created with
367an earlier version of the class. If you plan to have long-lived
368objects that will see many versions of a class, it may be worthwhile
369to put a version number in the objects so that suitable conversions
370can be made by the class's \method{__setstate__()} method.
Guido van Rossum470be141995-03-17 16:07:09 +0000371
Barry Warsawf595fd92001-11-15 23:39:07 +0000372\subsection{The pickle protocol
373\label{pickle-protocol}}\setindexsubitem{(pickle protocol)}
Fred Drake40748961998-03-06 21:27:14 +0000374
Barry Warsawf595fd92001-11-15 23:39:07 +0000375This section describes the ``pickling protocol'' that defines the
376interface between the pickler/unpickler and the objects that are being
377serialized. This protocol provides a standard way for you to define,
378customize, and control how your objects are serialized and
379de-serialized. The description in this section doesn't cover specific
380customizations that you can employ to make the unpickling environment
381safer from untrusted pickle data streams; see section~\ref{pickle-sec}
382for more details.
Fred Drake40748961998-03-06 21:27:14 +0000383
Barry Warsawf595fd92001-11-15 23:39:07 +0000384\subsubsection{Pickling and unpickling normal class
385 instances\label{pickle-inst}}
Fred Drake9b28fe21998-04-04 06:20:28 +0000386
Barry Warsawf595fd92001-11-15 23:39:07 +0000387When a pickled class instance is unpickled, its \method{__init__()}
388method is normally \emph{not} invoked. If it is desirable that the
389\method{__init__()} method be called on unpickling, a class can define
390a method \method{__getinitargs__()}, which should return a
391\emph{tuple} containing the arguments to be passed to the class
392constructor (i.e. \method{__init__()}). The
393\method{__getinitargs__()} method is called at
394pickle time; the tuple it returns is incorporated in the pickle for
395the instance.
396\withsubitem{(copy protocol)}{\ttindex{__getinitargs__()}}
397\withsubitem{(instance constructor)}{\ttindex{__init__()}}
Fred Drake17e56401998-04-11 20:43:51 +0000398
Barry Warsawf595fd92001-11-15 23:39:07 +0000399\withsubitem{(copy protocol)}{
400 \ttindex{__getstate__()}\ttindex{__setstate__()}}
401\withsubitem{(instance attribute)}{
402 \ttindex{__dict__}}
Fred Drake17e56401998-04-11 20:43:51 +0000403
Barry Warsawf595fd92001-11-15 23:39:07 +0000404Classes can further influence how their instances are pickled; if the
405class defines the method \method{__getstate__()}, it is called and the
406return state is pickled as the contents for the instance, instead of
407the contents of the instance's dictionary. If there is no
408\method{__getstate__()} method, the instance's \member{__dict__} is
409pickled.
Fred Drake9463de21998-04-11 20:05:43 +0000410
Barry Warsawf595fd92001-11-15 23:39:07 +0000411Upon unpickling, if the class also defines the method
412\method{__setstate__()}, it is called with the unpickled
413state\footnote{These methods can also be used to implement copying
414class instances.}. If there is no \method{__setstate__()} method, the
415pickled object must be a dictionary and its items are assigned to the
416new instance's dictionary. If a class defines both
417\method{__getstate__()} and \method{__setstate__()}, the state object
418needn't be a dictionary and these methods can do what they
419want\footnote{This protocol is also used by the shallow and deep
420copying operations defined in the
421\refmodule{copy} module.}.
422
423\subsubsection{Pickling and unpickling extension types}
424
425When the \class{Pickler} encounters an object of a type it knows
426nothing about --- such as an extension type --- it looks in two places
427for a hint of how to pickle it. One alternative is for the object to
428implement a \method{__reduce__()} method. If provided, at pickling
429time \method{__reduce__()} will be called with no arguments, and it
430must return either a string or a tuple.
431
432If a string is returned, it names a global variable whose contents are
433pickled as normal. When a tuple is returned, it must be of length two
434or three, with the following semantics:
435
436\begin{itemize}
437
438\item A callable object, which in the unpickling environment must be
439 either a class, a callable registered as a ``safe constructor''
440 (see below), or it must have an attribute
441 \member{__safe_for_unpickling__} with a true value. Otherwise,
442 an \exception{UnpicklingError} will be raised in the unpickling
443 environment. Note that as usual, the callable itself is pickled
444 by name.
445
446\item A tuple of arguments for the callable object, or \code{None}.
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000447\deprecated{2.3}{Use the tuple of arguments instead}
Barry Warsawf595fd92001-11-15 23:39:07 +0000448
449\item Optionally, the object's state, which will be passed to
450 the object's \method{__setstate__()} method as described in
451 section~\ref{pickle-inst}. If the object has no
452 \method{__setstate__()} method, then, as above, the value must
453 be a dictionary and it will be added to the object's
454 \member{__dict__}.
455
456\end{itemize}
457
458Upon unpickling, the callable will be called (provided that it meets
459the above criteria), passing in the tuple of arguments; it should
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000460return the unpickled object.
461
462If the second item was \code{None}, then instead of calling the
463callable directly, its \method{__basicnew__()} method is called
464without arguments. It should also return the unpickled object.
465
466\deprecated{2.3}{Use the tuple of arguments instead}
Barry Warsawf595fd92001-11-15 23:39:07 +0000467
468An alternative to implementing a \method{__reduce__()} method on the
469object to be pickled, is to register the callable with the
Fred Drake2744f432001-11-26 21:30:36 +0000470\refmodule[copyreg]{copy_reg} module. This module provides a way
Barry Warsawf595fd92001-11-15 23:39:07 +0000471for programs to register ``reduction functions'' and constructors for
472user-defined types. Reduction functions have the same semantics and
473interface as the \method{__reduce__()} method described above, except
474that they are called with a single argument, the object to be pickled.
475
476The registered constructor is deemed a ``safe constructor'' for purposes
477of unpickling as described above.
478
479\subsubsection{Pickling and unpickling external objects}
480
481For the benefit of object persistence, the \module{pickle} module
482supports the notion of a reference to an object outside the pickled
483data stream. Such objects are referenced by a ``persistent id'',
484which is just an arbitrary string of printable \ASCII{} characters.
485The resolution of such names is not defined by the \module{pickle}
486module; it will delegate this resolution to user defined functions on
487the pickler and unpickler\footnote{The actual mechanism for
488associating these user defined functions is slightly different for
489\module{pickle} and \module{cPickle}. The description given here
490works the same for both implementations. Users of the \module{pickle}
491module could also use subclassing to effect the same results,
492overriding the \method{persistent_id()} and \method{persistent_load()}
493methods in the derived classes.}.
494
495To define external persistent id resolution, you need to set the
496\member{persistent_id} attribute of the pickler object and the
497\member{persistent_load} attribute of the unpickler object.
498
499To pickle objects that have an external persistent id, the pickler
500must have a custom \function{persistent_id()} method that takes an
501object as an argument and returns either \code{None} or the persistent
502id for that object. When \code{None} is returned, the pickler simply
503pickles the object as normal. When a persistent id string is
504returned, the pickler will pickle that string, along with a marker
505so that the unpickler will recognize the string as a persistent id.
506
507To unpickle external objects, the unpickler must have a custom
508\function{persistent_load()} function that takes a persistent id
509string and returns the referenced object.
510
511Here's a silly example that \emph{might} shed more light:
512
513\begin{verbatim}
514import pickle
515from cStringIO import StringIO
516
517src = StringIO()
518p = pickle.Pickler(src)
519
520def persistent_id(obj):
521 if hasattr(obj, 'x'):
522 return 'the value %d' % obj.x
523 else:
524 return None
525
526p.persistent_id = persistent_id
527
528class Integer:
529 def __init__(self, x):
530 self.x = x
531 def __str__(self):
532 return 'My name is integer %d' % self.x
533
534i = Integer(7)
535print i
536p.dump(i)
537
538datastream = src.getvalue()
539print repr(datastream)
540dst = StringIO(datastream)
541
542up = pickle.Unpickler(dst)
543
544class FancyInteger(Integer):
545 def __str__(self):
546 return 'I am the integer %d' % self.x
547
548def persistent_load(persid):
549 if persid.startswith('the value '):
550 value = int(persid.split()[2])
551 return FancyInteger(value)
552 else:
553 raise pickle.UnpicklingError, 'Invalid persistent id'
554
555up.persistent_load = persistent_load
556
557j = up.load()
558print j
559\end{verbatim}
560
561In the \module{cPickle} module, the unpickler's
562\member{persistent_load} attribute can also be set to a Python
563list, in which case, when the unpickler reaches a persistent id, the
564persistent id string will simply be appended to this list. This
565functionality exists so that a pickle data stream can be ``sniffed''
566for object references without actually instantiating all the objects
567in a pickle\footnote{We'll leave you with the image of Guido and Jim
568sitting around sniffing pickles in their living rooms.}. Setting
569\member{persistent_load} to a list is usually used in conjunction with
570the \method{noload()} method on the Unpickler.
571
572% BAW: Both pickle and cPickle support something called
573% inst_persistent_id() which appears to give unknown types a second
574% shot at producing a persistent id. Since Jim Fulton can't remember
575% why it was added or what it's for, I'm leaving it undocumented.
576
577\subsection{Security \label{pickle-sec}}
578
579Most of the security issues surrounding the \module{pickle} and
580\module{cPickle} module involve unpickling. There are no known
581security vulnerabilities
582related to pickling because you (the programmer) control the objects
583that \module{pickle} will interact with, and all it produces is a
584string.
585
586However, for unpickling, it is \strong{never} a good idea to unpickle
587an untrusted string whose origins are dubious, for example, strings
588read from a socket. This is because unpickling can create unexpected
589objects and even potentially run methods of those objects, such as
590their class constructor or destructor\footnote{A special note of
591caution is worth raising about the \refmodule{Cookie}
592module. By default, the \class{Cookie.Cookie} class is an alias for
593the \class{Cookie.SmartCookie} class, which ``helpfully'' attempts to
594unpickle any cookie data string it is passed. This is a huge security
595hole because cookie data typically comes from an untrusted source.
596You should either explicitly use the \class{Cookie.SimpleCookie} class
597--- which doesn't attempt to unpickle its string --- or you should
598implement the defensive programming steps described later on in this
599section.}.
600
601You can defend against this by customizing your unpickler so that you
602can control exactly what gets unpickled and what gets called.
603Unfortunately, exactly how you do this is different depending on
604whether you're using \module{pickle} or \module{cPickle}.
605
606One common feature that both modules implement is the
607\member{__safe_for_unpickling__} attribute. Before calling a callable
608which is not a class, the unpickler will check to make sure that the
609callable has either been registered as a safe callable via the
Fred Drake2744f432001-11-26 21:30:36 +0000610\refmodule[copyreg]{copy_reg} module, or that it has an
Barry Warsawf595fd92001-11-15 23:39:07 +0000611attribute \member{__safe_for_unpickling__} with a true value. This
612prevents the unpickling environment from being tricked into doing
613evil things like call \code{os.unlink()} with an arbitrary file name.
614See section~\ref{pickle-protocol} for more details.
615
616For safely unpickling class instances, you need to control exactly
Barry Warsaw69ab5832001-11-18 16:24:01 +0000617which classes will get created. Be aware that a class's constructor
618could be called (if the pickler found a \method{__getinitargs__()}
619method) and the the class's destructor (i.e. its \method{__del__()} method)
620might get called when the object is garbage collected. Depending on
621the class, it isn't very heard to trick either method into doing bad
622things, such as removing a file. The way to
Barry Warsawf595fd92001-11-15 23:39:07 +0000623control the classes that are safe to instantiate differs in
624\module{pickle} and \module{cPickle}\footnote{A word of caution: the
625mechanisms described here use internal attributes and methods, which
626are subject to change in future versions of Python. We intend to
627someday provide a common interface for controlling this behavior,
628which will work in either \module{pickle} or \module{cPickle}.}.
629
630In the \module{pickle} module, you need to derive a subclass from
631\class{Unpickler}, overriding the \method{load_global()}
632method. \method{load_global()} should read two lines from the pickle
633data stream where the first line will the the name of the module
634containing the class and the second line will be the name of the
635instance's class. It then look up the class, possibly importing the
636module and digging out the attribute, then it appends what it finds to
637the unpickler's stack. Later on, this class will be assigned to the
638\member{__class__} attribute of an empty class, as a way of magically
639creating an instance without calling its class's \method{__init__()}.
640You job (should you choose to accept it), would be to have
641\method{load_global()} push onto the unpickler's stack, a known safe
642version of any class you deem safe to unpickle. It is up to you to
643produce such a class. Or you could raise an error if you want to
644disallow all unpickling of instances. If this sounds like a hack,
645you're right. UTSL.
646
647Things are a little cleaner with \module{cPickle}, but not by much.
648To control what gets unpickled, you can set the unpickler's
649\member{find_global} attribute to a function or \code{None}. If it is
650\code{None} then any attempts to unpickle instances will raise an
651\exception{UnpicklingError}. If it is a function,
652then it should accept a module name and a class name, and return the
653corresponding class object. It is responsible for looking up the
654class, again performing any necessary imports, and it may raise an
655error to prevent instances of the class from being unpickled.
656
657The moral of the story is that you should be really careful about the
658source of the strings your application unpickles.
Fred Drake9463de21998-04-11 20:05:43 +0000659
Fred Drake38e5d272000-04-03 20:13:55 +0000660\subsection{Example \label{pickle-example}}
661
662Here's a simple example of how to modify pickling behavior for a
663class. The \class{TextReader} class opens a text file, and returns
664the line number and line contents each time its \method{readline()}
665method is called. If a \class{TextReader} instance is pickled, all
666attributes \emph{except} the file object member are saved. When the
667instance is unpickled, the file is reopened, and reading resumes from
668the last location. The \method{__setstate__()} and
669\method{__getstate__()} methods are used to implement this behavior.
670
671\begin{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000672class TextReader:
Fred Drakec8252802001-09-25 16:29:17 +0000673 """Print and number lines in a text file."""
674 def __init__(self, file):
Fred Drake38e5d272000-04-03 20:13:55 +0000675 self.file = file
Fred Drakec8252802001-09-25 16:29:17 +0000676 self.fh = open(file)
Fred Drake38e5d272000-04-03 20:13:55 +0000677 self.lineno = 0
678
679 def readline(self):
680 self.lineno = self.lineno + 1
681 line = self.fh.readline()
682 if not line:
683 return None
Fred Drakec8252802001-09-25 16:29:17 +0000684 if line.endswith("\n"):
685 line = line[:-1]
686 return "%d: %s" % (self.lineno, line)
Fred Drake38e5d272000-04-03 20:13:55 +0000687
Fred Drake38e5d272000-04-03 20:13:55 +0000688 def __getstate__(self):
Fred Drakec8252802001-09-25 16:29:17 +0000689 odict = self.__dict__.copy() # copy the dict since we change it
690 del odict['fh'] # remove filehandle entry
Fred Drake38e5d272000-04-03 20:13:55 +0000691 return odict
692
Fred Drake38e5d272000-04-03 20:13:55 +0000693 def __setstate__(self,dict):
Fred Drakec8252802001-09-25 16:29:17 +0000694 fh = open(dict['file']) # reopen file
695 count = dict['lineno'] # read from file...
696 while count: # until line count is restored
Fred Drake38e5d272000-04-03 20:13:55 +0000697 fh.readline()
698 count = count - 1
Fred Drakec8252802001-09-25 16:29:17 +0000699 self.__dict__.update(dict) # update attributes
700 self.fh = fh # save the file object
Fred Drake38e5d272000-04-03 20:13:55 +0000701\end{verbatim}
702
703A sample usage might be something like this:
704
705\begin{verbatim}
706>>> import TextReader
707>>> obj = TextReader.TextReader("TextReader.py")
708>>> obj.readline()
709'1: #!/usr/local/bin/python'
710>>> # (more invocations of obj.readline() here)
711... obj.readline()
712'7: class TextReader:'
713>>> import pickle
714>>> pickle.dump(obj,open('save.p','w'))
Fred Drakec8252802001-09-25 16:29:17 +0000715\end{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000716
Fred Drakec8252802001-09-25 16:29:17 +0000717If you want to see that \refmodule{pickle} works across Python
718processes, start another Python session, before continuing. What
719follows can happen from either the same process or a new process.
Fred Drake38e5d272000-04-03 20:13:55 +0000720
Fred Drakec8252802001-09-25 16:29:17 +0000721\begin{verbatim}
Fred Drake38e5d272000-04-03 20:13:55 +0000722>>> import pickle
723>>> reader = pickle.load(open('save.p'))
724>>> reader.readline()
725'8: "Print and number lines in a text file."'
726\end{verbatim}
727
728
Barry Warsawf595fd92001-11-15 23:39:07 +0000729\begin{seealso}
730 \seemodule[copyreg]{copy_reg}{Pickle interface constructor
731 registration for extension types.}
732
733 \seemodule{shelve}{Indexed databases of objects; uses \module{pickle}.}
734
735 \seemodule{copy}{Shallow and deep object copying.}
736
737 \seemodule{marshal}{High-performance serialization of built-in types.}
738\end{seealso}
739
740
741\section{\module{cPickle} --- A faster \module{pickle}}
Fred Drakeffbe6871999-04-22 21:23:22 +0000742
Fred Drakeb91e9341998-07-23 17:59:49 +0000743\declaremodule{builtin}{cPickle}
Fred Drake38e5d272000-04-03 20:13:55 +0000744\modulesynopsis{Faster version of \refmodule{pickle}, but not subclassable.}
Fred Drakeffbe6871999-04-22 21:23:22 +0000745\moduleauthor{Jim Fulton}{jfulton@digicool.com}
746\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
Fred Drakeb91e9341998-07-23 17:59:49 +0000747
Barry Warsawf595fd92001-11-15 23:39:07 +0000748The \module{cPickle} module supports serialization and
749de-serialization of Python objects, providing an interface and
750functionality nearly identical to the
751\refmodule{pickle}\refstmodindex{pickle} module. There are several
752differences, the most important being performance and subclassability.
Fred Drake9463de21998-04-11 20:05:43 +0000753
Barry Warsawf595fd92001-11-15 23:39:07 +0000754First, \module{cPickle} can be up to 1000 times faster than
755\module{pickle} because the former is implemented in C. Second, in
756the \module{cPickle} module the callables \function{Pickler()} and
757\function{Unpickler()} are functions, not classes. This means that
758you cannot use them to derive custom pickling and unpickling
759subclasses. Most applications have no need for this functionality and
760should benefit from the greatly improved performance of the
761\module{cPickle} module.
Fred Drake9463de21998-04-11 20:05:43 +0000762
Barry Warsawf595fd92001-11-15 23:39:07 +0000763The pickle data stream produced by \module{pickle} and
764\module{cPickle} are identical, so it is possible to use
765\module{pickle} and \module{cPickle} interchangeably with existing
766pickles\footnote{Since the pickle data format is actually a tiny
767stack-oriented programming language, and some freedom is taken in the
768encodings of certain objects, it is possible that the two modules
769produce different data streams for the same input objects. However it
770is guaranteed that they will always be able to read each other's
771data streams.}.
Guido van Rossumcf3ce921999-01-06 23:34:39 +0000772
Barry Warsawf595fd92001-11-15 23:39:07 +0000773There are additional minor differences in API between \module{cPickle}
774and \module{pickle}, however for most applications, they are
775interchangable. More documentation is provided in the
776\module{pickle} module documentation, which
777includes a list of the documented differences.
778
779