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