Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :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 Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 14 | .. sectionauthor:: Jim Kerr <jbkerr@sr.hp.com>. |
| 15 | .. sectionauthor:: Barry Warsaw <barry@zope.com> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 17 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | The :mod:`pickle` module implements a fundamental, but powerful algorithm for |
| 19 | serializing and de-serializing a Python object structure. "Pickling" is the |
| 20 | process whereby a Python object hierarchy is converted into a byte stream, and |
| 21 | "unpickling" is the inverse operation, whereby a byte stream is converted back |
| 22 | into an object hierarchy. Pickling (and unpickling) is alternatively known as |
| 23 | "serialization", "marshalling," [#]_ or "flattening", however, to avoid |
Benjamin Peterson | be149d0 | 2008-06-20 21:03:22 +0000 | [diff] [blame] | 24 | confusion, the terms used here are "pickling" and "unpickling".. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 25 | |
Georg Brandl | 0036bcf | 2010-10-17 10:24:54 +0000 | [diff] [blame] | 26 | .. warning:: |
| 27 | |
| 28 | The :mod:`pickle` module is not intended to be secure against erroneous or |
| 29 | maliciously constructed data. Never unpickle data received from an untrusted |
| 30 | or unauthenticated source. |
| 31 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 32 | |
| 33 | Relationship to other Python modules |
| 34 | ------------------------------------ |
| 35 | |
Benjamin Peterson | be149d0 | 2008-06-20 21:03:22 +0000 | [diff] [blame] | 36 | The :mod:`pickle` module has an transparent optimizer (:mod:`_pickle`) written |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 37 | in C. It is used whenever available. Otherwise the pure Python implementation is |
Benjamin Peterson | be149d0 | 2008-06-20 21:03:22 +0000 | [diff] [blame] | 38 | used. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 39 | |
| 40 | Python has a more primitive serialization module called :mod:`marshal`, but in |
| 41 | general :mod:`pickle` should always be the preferred way to serialize Python |
| 42 | objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc` |
| 43 | files. |
| 44 | |
Georg Brandl | 5aa580f | 2010-11-30 14:57:54 +0000 | [diff] [blame] | 45 | The :mod:`pickle` module differs from :mod:`marshal` in several significant ways: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 46 | |
| 47 | * The :mod:`pickle` module keeps track of the objects it has already serialized, |
| 48 | so that later references to the same object won't be serialized again. |
| 49 | :mod:`marshal` doesn't do this. |
| 50 | |
| 51 | This has implications both for recursive objects and object sharing. Recursive |
| 52 | objects are objects that contain references to themselves. These are not |
| 53 | handled by marshal, and in fact, attempting to marshal recursive objects will |
| 54 | crash your Python interpreter. Object sharing happens when there are multiple |
| 55 | references to the same object in different places in the object hierarchy being |
| 56 | serialized. :mod:`pickle` stores such objects only once, and ensures that all |
| 57 | other references point to the master copy. Shared objects remain shared, which |
| 58 | can be very important for mutable objects. |
| 59 | |
| 60 | * :mod:`marshal` cannot be used to serialize user-defined classes and their |
| 61 | instances. :mod:`pickle` can save and restore class instances transparently, |
| 62 | however the class definition must be importable and live in the same module as |
| 63 | when the object was stored. |
| 64 | |
| 65 | * The :mod:`marshal` serialization format is not guaranteed to be portable |
| 66 | across Python versions. Because its primary job in life is to support |
| 67 | :file:`.pyc` files, the Python implementers reserve the right to change the |
| 68 | serialization format in non-backwards compatible ways should the need arise. |
| 69 | The :mod:`pickle` serialization format is guaranteed to be backwards compatible |
| 70 | across Python releases. |
| 71 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 72 | Note that serialization is a more primitive notion than persistence; although |
| 73 | :mod:`pickle` reads and writes file objects, it does not handle the issue of |
| 74 | naming persistent objects, nor the (even more complicated) issue of concurrent |
| 75 | access to persistent objects. The :mod:`pickle` module can transform a complex |
| 76 | object into a byte stream and it can transform the byte stream into an object |
| 77 | with the same internal structure. Perhaps the most obvious thing to do with |
| 78 | these byte streams is to write them onto a file, but it is also conceivable to |
| 79 | send them across a network or store them in a database. The module |
| 80 | :mod:`shelve` provides a simple interface to pickle and unpickle objects on |
| 81 | DBM-style database files. |
| 82 | |
| 83 | |
| 84 | Data stream format |
| 85 | ------------------ |
| 86 | |
| 87 | .. index:: |
| 88 | single: XDR |
| 89 | single: External Data Representation |
| 90 | |
| 91 | The data format used by :mod:`pickle` is Python-specific. This has the |
| 92 | advantage that there are no restrictions imposed by external standards such as |
| 93 | XDR (which can't represent pointer sharing); however it means that non-Python |
| 94 | programs may not be able to reconstruct pickled Python objects. |
| 95 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 96 | By default, the :mod:`pickle` data format uses a compact binary representation. |
| 97 | The module :mod:`pickletools` contains tools for analyzing data streams |
| 98 | generated by :mod:`pickle`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 | |
Georg Brandl | 42f2ae0 | 2008-04-06 08:39:37 +0000 | [diff] [blame] | 100 | There are currently 4 different protocols which can be used for pickling. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 101 | |
Alexandre Vassalotti | f7d08c7 | 2009-01-23 04:50:05 +0000 | [diff] [blame] | 102 | * Protocol version 0 is the original human-readable protocol and is |
| 103 | backwards compatible with earlier versions of Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 104 | |
| 105 | * Protocol version 1 is the old binary format which is also compatible with |
| 106 | earlier versions of Python. |
| 107 | |
| 108 | * Protocol version 2 was introduced in Python 2.3. It provides much more |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 109 | efficient pickling of :term:`new-style class`\es. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | |
Georg Brandl | 42f2ae0 | 2008-04-06 08:39:37 +0000 | [diff] [blame] | 111 | * Protocol version 3 was added in Python 3.0. It has explicit support for |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 112 | bytes and cannot be unpickled by Python 2.x pickle modules. This is |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 113 | the current recommended protocol, use it whenever it is possible. |
Georg Brandl | 42f2ae0 | 2008-04-06 08:39:37 +0000 | [diff] [blame] | 114 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 115 | Refer to :pep:`307` for information about improvements brought by |
| 116 | protocol 2. See :mod:`pickletools`'s source code for extensive |
| 117 | comments about opcodes used by pickle protocols. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 118 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 119 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 120 | Module Interface |
| 121 | ---------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | |
| 123 | To serialize an object hierarchy, you first create a pickler, then you call the |
| 124 | pickler's :meth:`dump` method. To de-serialize a data stream, you first create |
| 125 | an unpickler, then you call the unpickler's :meth:`load` method. The |
| 126 | :mod:`pickle` module provides the following constant: |
| 127 | |
| 128 | |
| 129 | .. data:: HIGHEST_PROTOCOL |
| 130 | |
| 131 | The highest protocol version available. This value can be passed as a |
| 132 | *protocol* value. |
| 133 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 134 | .. data:: DEFAULT_PROTOCOL |
| 135 | |
| 136 | The default protocol used for pickling. May be less than HIGHEST_PROTOCOL. |
| 137 | Currently the default protocol is 3; a backward-incompatible protocol |
| 138 | designed for Python 3.0. |
| 139 | |
| 140 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 141 | The :mod:`pickle` module provides the following functions to make the pickling |
| 142 | process more convenient: |
| 143 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 144 | .. function:: dump(obj, file, protocol=None, \*, fix_imports=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 145 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 146 | Write a pickled representation of *obj* to the open :term:`file object` *file*. |
| 147 | This is equivalent to ``Pickler(file, protocol).dump(obj)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 148 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 149 | The optional *protocol* argument tells the pickler to use the given protocol; |
| 150 | supported protocols are 0, 1, 2, 3. The default protocol is 3; a |
| 151 | backward-incompatible protocol designed for Python 3.0. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 152 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 153 | Specifying a negative protocol version selects the highest protocol version |
| 154 | supported. The higher the protocol used, the more recent the version of |
| 155 | Python needed to read the pickle produced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 156 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 157 | The *file* argument must have a write() method that accepts a single bytes |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 158 | argument. It can thus be an on-disk file opened for binary writing, a |
| 159 | :class:`io.BytesIO` instance, or any other custom object that meets this |
| 160 | interface. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 161 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 162 | If *fix_imports* is True and *protocol* is less than 3, pickle will try to |
| 163 | map the new Python 3.x names to the old module names used in Python 2.x, |
| 164 | so that the pickle data stream is readable with Python 2.x. |
| 165 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 166 | .. function:: dumps(obj, protocol=None, \*, fix_imports=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | |
Mark Summerfield | b9e2304 | 2008-04-21 14:47:45 +0000 | [diff] [blame] | 168 | Return the pickled representation of the object as a :class:`bytes` |
| 169 | object, instead of writing it to a file. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 170 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 171 | The optional *protocol* argument tells the pickler to use the given protocol; |
| 172 | supported protocols are 0, 1, 2, 3. The default protocol is 3; a |
| 173 | backward-incompatible protocol designed for Python 3.0. |
| 174 | |
| 175 | Specifying a negative protocol version selects the highest protocol version |
| 176 | supported. The higher the protocol used, the more recent the version of |
| 177 | Python needed to read the pickle produced. |
| 178 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 179 | If *fix_imports* is True and *protocol* is less than 3, pickle will try to |
| 180 | map the new Python 3.x names to the old module names used in Python 2.x, |
| 181 | so that the pickle data stream is readable with Python 2.x. |
| 182 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 183 | .. function:: load(file, \*, fix_imports=True, encoding="ASCII", errors="strict") |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 184 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 185 | Read a pickled object representation from the open :term:`file object` *file* |
| 186 | and return the reconstituted object hierarchy specified therein. This is |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 187 | equivalent to ``Unpickler(file).load()``. |
| 188 | |
| 189 | The protocol version of the pickle is detected automatically, so no protocol |
| 190 | argument is needed. Bytes past the pickled object's representation are |
| 191 | ignored. |
| 192 | |
| 193 | The argument *file* must have two methods, a read() method that takes an |
| 194 | integer argument, and a readline() method that requires no arguments. Both |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 195 | methods should return bytes. Thus *file* can be an on-disk file opened |
| 196 | for binary reading, a :class:`io.BytesIO` object, or any other custom object |
| 197 | that meets this interface. |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 198 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 199 | Optional keyword arguments are *fix_imports*, *encoding* and *errors*, |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 200 | which are used to control compatibility support for pickle stream generated |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 201 | by Python 2.x. If *fix_imports* is True, pickle will try to map the old |
| 202 | Python 2.x names to the new names used in Python 3.x. The *encoding* and |
| 203 | *errors* tell pickle how to decode 8-bit string instances pickled by Python |
| 204 | 2.x; these default to 'ASCII' and 'strict', respectively. |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 205 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 206 | .. function:: loads(bytes_object, \*, fix_imports=True, encoding="ASCII", errors="strict") |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 207 | |
| 208 | Read a pickled object hierarchy from a :class:`bytes` object and return the |
| 209 | reconstituted object hierarchy specified therein |
| 210 | |
| 211 | The protocol version of the pickle is detected automatically, so no protocol |
| 212 | argument is needed. Bytes past the pickled object's representation are |
| 213 | ignored. |
| 214 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 215 | Optional keyword arguments are *fix_imports*, *encoding* and *errors*, |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 216 | which are used to control compatibility support for pickle stream generated |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 217 | by Python 2.x. If *fix_imports* is True, pickle will try to map the old |
| 218 | Python 2.x names to the new names used in Python 3.x. The *encoding* and |
| 219 | *errors* tell pickle how to decode 8-bit string instances pickled by Python |
| 220 | 2.x; these default to 'ASCII' and 'strict', respectively. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 221 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 223 | The :mod:`pickle` module defines three exceptions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | |
| 225 | .. exception:: PickleError |
| 226 | |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 227 | Common base class for the other pickling exceptions. It inherits |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | :exc:`Exception`. |
| 229 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 230 | .. exception:: PicklingError |
| 231 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 232 | Error raised when an unpicklable object is encountered by :class:`Pickler`. |
| 233 | It inherits :exc:`PickleError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 235 | Refer to :ref:`pickle-picklable` to learn what kinds of objects can be |
| 236 | pickled. |
| 237 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 238 | .. exception:: UnpicklingError |
| 239 | |
Ezio Melotti | e62aad3 | 2011-11-18 13:51:10 +0200 | [diff] [blame] | 240 | Error raised when there is a problem unpickling an object, such as a data |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 241 | corruption or a security violation. It inherits :exc:`PickleError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 242 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 243 | Note that other exceptions may also be raised during unpickling, including |
| 244 | (but not necessarily limited to) AttributeError, EOFError, ImportError, and |
| 245 | IndexError. |
| 246 | |
| 247 | |
| 248 | The :mod:`pickle` module exports two classes, :class:`Pickler` and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | :class:`Unpickler`: |
| 250 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 251 | .. class:: Pickler(file, protocol=None, \*, fix_imports=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 252 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 253 | This takes a binary file for writing a pickle data stream. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 254 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 255 | The optional *protocol* argument tells the pickler to use the given protocol; |
| 256 | supported protocols are 0, 1, 2, 3. The default protocol is 3; a |
| 257 | backward-incompatible protocol designed for Python 3.0. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 258 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 259 | Specifying a negative protocol version selects the highest protocol version |
| 260 | supported. The higher the protocol used, the more recent the version of |
| 261 | Python needed to read the pickle produced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 262 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 263 | The *file* argument must have a write() method that accepts a single bytes |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 264 | argument. It can thus be an on-disk file opened for binary writing, a |
| 265 | :class:`io.BytesIO` instance, or any other custom object that meets this interface. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 266 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 267 | If *fix_imports* is True and *protocol* is less than 3, pickle will try to |
| 268 | map the new Python 3.x names to the old module names used in Python 2.x, |
| 269 | so that the pickle data stream is readable with Python 2.x. |
| 270 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 271 | .. method:: dump(obj) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 272 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 273 | Write a pickled representation of *obj* to the open file object given in |
| 274 | the constructor. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 275 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 276 | .. method:: persistent_id(obj) |
| 277 | |
| 278 | Do nothing by default. This exists so a subclass can override it. |
| 279 | |
| 280 | If :meth:`persistent_id` returns ``None``, *obj* is pickled as usual. Any |
| 281 | other value causes :class:`Pickler` to emit the returned value as a |
| 282 | persistent ID for *obj*. The meaning of this persistent ID should be |
| 283 | defined by :meth:`Unpickler.persistent_load`. Note that the value |
| 284 | returned by :meth:`persistent_id` cannot itself have a persistent ID. |
| 285 | |
| 286 | See :ref:`pickle-persistent` for details and examples of uses. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 287 | |
Antoine Pitrou | 8d3c290 | 2012-03-04 18:31:48 +0100 | [diff] [blame^] | 288 | .. attribute:: dispatch_table |
| 289 | |
| 290 | A pickler object's dispatch table is a registry of *reduction |
| 291 | functions* of the kind which can be declared using |
| 292 | :func:`copyreg.pickle`. It is a mapping whose keys are classes |
| 293 | and whose values are reduction functions. A reduction function |
| 294 | takes a single argument of the associated class and should |
| 295 | conform to the same interface as a :meth:`~object.__reduce__` |
| 296 | method. |
| 297 | |
| 298 | By default, a pickler object will not have a |
| 299 | :attr:`dispatch_table` attribute, and it will instead use the |
| 300 | global dispatch table managed by the :mod:`copyreg` module. |
| 301 | However, to customize the pickling for a specific pickler object |
| 302 | one can set the :attr:`dispatch_table` attribute to a dict-like |
| 303 | object. Alternatively, if a subclass of :class:`Pickler` has a |
| 304 | :attr:`dispatch_table` attribute then this will be used as the |
| 305 | default dispatch table for instances of that class. |
| 306 | |
| 307 | See :ref:`pickle-dispatch` for usage examples. |
| 308 | |
| 309 | .. versionadded:: 3.3 |
| 310 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 311 | .. attribute:: fast |
| 312 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 313 | Deprecated. Enable fast mode if set to a true value. The fast mode |
| 314 | disables the usage of memo, therefore speeding the pickling process by not |
| 315 | generating superfluous PUT opcodes. It should not be used with |
| 316 | self-referential objects, doing otherwise will cause :class:`Pickler` to |
| 317 | recurse infinitely. |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 318 | |
| 319 | Use :func:`pickletools.optimize` if you need more compact pickles. |
| 320 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 321 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 322 | .. class:: Unpickler(file, \*, fix_imports=True, encoding="ASCII", errors="strict") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 323 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 324 | This takes a binary file for reading a pickle data stream. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 325 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 326 | The protocol version of the pickle is detected automatically, so no |
| 327 | protocol argument is needed. |
| 328 | |
| 329 | The argument *file* must have two methods, a read() method that takes an |
| 330 | integer argument, and a readline() method that requires no arguments. Both |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 331 | methods should return bytes. Thus *file* can be an on-disk file object opened |
| 332 | for binary reading, a :class:`io.BytesIO` object, or any other custom object |
| 333 | that meets this interface. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 334 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 335 | Optional keyword arguments are *fix_imports*, *encoding* and *errors*, |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 336 | which are used to control compatibility support for pickle stream generated |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 337 | by Python 2.x. If *fix_imports* is True, pickle will try to map the old |
| 338 | Python 2.x names to the new names used in Python 3.x. The *encoding* and |
| 339 | *errors* tell pickle how to decode 8-bit string instances pickled by Python |
| 340 | 2.x; these default to 'ASCII' and 'strict', respectively. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 341 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 342 | .. method:: load() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 343 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 344 | Read a pickled object representation from the open file object given in |
| 345 | the constructor, and return the reconstituted object hierarchy specified |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 346 | therein. Bytes past the pickled object's representation are ignored. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 347 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 348 | .. method:: persistent_load(pid) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 349 | |
Ezio Melotti | e62aad3 | 2011-11-18 13:51:10 +0200 | [diff] [blame] | 350 | Raise an :exc:`UnpicklingError` by default. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 351 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 352 | If defined, :meth:`persistent_load` should return the object specified by |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 353 | the persistent ID *pid*. If an invalid persistent ID is encountered, an |
Ezio Melotti | e62aad3 | 2011-11-18 13:51:10 +0200 | [diff] [blame] | 354 | :exc:`UnpicklingError` should be raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 355 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 356 | See :ref:`pickle-persistent` for details and examples of uses. |
| 357 | |
| 358 | .. method:: find_class(module, name) |
| 359 | |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 360 | Import *module* if necessary and return the object called *name* from it, |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 361 | where the *module* and *name* arguments are :class:`str` objects. Note, |
| 362 | unlike its name suggests, :meth:`find_class` is also used for finding |
| 363 | functions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 364 | |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 365 | Subclasses may override this to gain control over what type of objects and |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 366 | how they can be loaded, potentially reducing security risks. Refer to |
| 367 | :ref:`pickle-restrict` for details. |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 368 | |
| 369 | |
| 370 | .. _pickle-picklable: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 371 | |
| 372 | What can be pickled and unpickled? |
| 373 | ---------------------------------- |
| 374 | |
| 375 | The following types can be pickled: |
| 376 | |
| 377 | * ``None``, ``True``, and ``False`` |
| 378 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 379 | * integers, floating point numbers, complex numbers |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 380 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 381 | * strings, bytes, bytearrays |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 382 | |
| 383 | * tuples, lists, sets, and dictionaries containing only picklable objects |
| 384 | |
| 385 | * functions defined at the top level of a module |
| 386 | |
| 387 | * built-in functions defined at the top level of a module |
| 388 | |
| 389 | * classes that are defined at the top level of a module |
| 390 | |
| 391 | * instances of such classes whose :attr:`__dict__` or :meth:`__setstate__` is |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 392 | picklable (see section :ref:`pickle-inst` for details) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 393 | |
| 394 | Attempts to pickle unpicklable objects will raise the :exc:`PicklingError` |
| 395 | exception; when this happens, an unspecified number of bytes may have already |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 396 | been written to the underlying file. Trying to pickle a highly recursive data |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 397 | structure may exceed the maximum recursion depth, a :exc:`RuntimeError` will be |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 398 | raised in this case. You can carefully raise this limit with |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 399 | :func:`sys.setrecursionlimit`. |
| 400 | |
| 401 | Note that functions (built-in and user-defined) are pickled by "fully qualified" |
| 402 | name reference, not by value. This means that only the function name is |
Ezio Melotti | e62aad3 | 2011-11-18 13:51:10 +0200 | [diff] [blame] | 403 | pickled, along with the name of the module the function is defined in. Neither the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 404 | function's code, nor any of its function attributes are pickled. Thus the |
| 405 | defining module must be importable in the unpickling environment, and the module |
| 406 | must contain the named object, otherwise an exception will be raised. [#]_ |
| 407 | |
| 408 | Similarly, classes are pickled by named reference, so the same restrictions in |
| 409 | the unpickling environment apply. Note that none of the class's code or data is |
| 410 | pickled, so in the following example the class attribute ``attr`` is not |
| 411 | restored in the unpickling environment:: |
| 412 | |
| 413 | class Foo: |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 414 | attr = 'A class attribute' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 415 | |
| 416 | picklestring = pickle.dumps(Foo) |
| 417 | |
| 418 | These restrictions are why picklable functions and classes must be defined in |
| 419 | the top level of a module. |
| 420 | |
| 421 | Similarly, when class instances are pickled, their class's code and data are not |
| 422 | pickled along with them. Only the instance data are pickled. This is done on |
| 423 | purpose, so you can fix bugs in a class or add methods to the class and still |
| 424 | load objects that were created with an earlier version of the class. If you |
| 425 | plan to have long-lived objects that will see many versions of a class, it may |
| 426 | be worthwhile to put a version number in the objects so that suitable |
| 427 | conversions can be made by the class's :meth:`__setstate__` method. |
| 428 | |
| 429 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 430 | .. _pickle-inst: |
| 431 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 432 | Pickling Class Instances |
| 433 | ------------------------ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 434 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 435 | In this section, we describe the general mechanisms available to you to define, |
| 436 | customize, and control how class instances are pickled and unpickled. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 437 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 438 | In most cases, no additional code is needed to make instances picklable. By |
| 439 | default, pickle will retrieve the class and the attributes of an instance via |
| 440 | introspection. When a class instance is unpickled, its :meth:`__init__` method |
| 441 | is usually *not* invoked. The default behaviour first creates an uninitialized |
| 442 | instance and then restores the saved attributes. The following code shows an |
| 443 | implementation of this behaviour:: |
Georg Brandl | 85eb8c1 | 2007-08-31 16:33:38 +0000 | [diff] [blame] | 444 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 445 | def save(obj): |
| 446 | return (obj.__class__, obj.__dict__) |
| 447 | |
| 448 | def load(cls, attributes): |
| 449 | obj = cls.__new__(cls) |
| 450 | obj.__dict__.update(attributes) |
| 451 | return obj |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 452 | |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 453 | Classes can alter the default behaviour by providing one or several special |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 454 | methods: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 455 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 456 | .. method:: object.__getnewargs__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 457 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 458 | In protocol 2 and newer, classes that implements the :meth:`__getnewargs__` |
| 459 | method can dictate the values passed to the :meth:`__new__` method upon |
| 460 | unpickling. This is often needed for classes whose :meth:`__new__` method |
| 461 | requires arguments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 462 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 463 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 464 | .. method:: object.__getstate__() |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 465 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 466 | Classes can further influence how their instances are pickled; if the class |
| 467 | defines the method :meth:`__getstate__`, it is called and the returned object |
| 468 | is pickled as the contents for the instance, instead of the contents of the |
| 469 | instance's dictionary. If the :meth:`__getstate__` method is absent, the |
| 470 | instance's :attr:`__dict__` is pickled as usual. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 471 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 472 | |
| 473 | .. method:: object.__setstate__(state) |
| 474 | |
| 475 | Upon unpickling, if the class defines :meth:`__setstate__`, it is called with |
| 476 | the unpickled state. In that case, there is no requirement for the state |
| 477 | object to be a dictionary. Otherwise, the pickled state must be a dictionary |
| 478 | and its items are assigned to the new instance's dictionary. |
| 479 | |
| 480 | .. note:: |
| 481 | |
| 482 | If :meth:`__getstate__` returns a false value, the :meth:`__setstate__` |
| 483 | method will not be called upon unpickling. |
| 484 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 485 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 486 | Refer to the section :ref:`pickle-state` for more information about how to use |
| 487 | the methods :meth:`__getstate__` and :meth:`__setstate__`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 488 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 489 | .. note:: |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 490 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 491 | At unpickling time, some methods like :meth:`__getattr__`, |
| 492 | :meth:`__getattribute__`, or :meth:`__setattr__` may be called upon the |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 493 | instance. In case those methods rely on some internal invariant being true, |
| 494 | the type should implement :meth:`__getnewargs__` to establish such an |
| 495 | invariant; otherwise, neither :meth:`__new__` nor :meth:`__init__` will be |
| 496 | called. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 497 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 498 | .. index:: pair: copy; protocol |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 499 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 500 | As we shall see, pickle does not use directly the methods described above. In |
| 501 | fact, these methods are part of the copy protocol which implements the |
| 502 | :meth:`__reduce__` special method. The copy protocol provides a unified |
| 503 | interface for retrieving the data necessary for pickling and copying |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 504 | objects. [#]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 505 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 506 | Although powerful, implementing :meth:`__reduce__` directly in your classes is |
| 507 | error prone. For this reason, class designers should use the high-level |
| 508 | interface (i.e., :meth:`__getnewargs__`, :meth:`__getstate__` and |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 509 | :meth:`__setstate__`) whenever possible. We will show, however, cases where |
| 510 | using :meth:`__reduce__` is the only option or leads to more efficient pickling |
| 511 | or both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 512 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 513 | .. method:: object.__reduce__() |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 514 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 515 | The interface is currently defined as follows. The :meth:`__reduce__` method |
| 516 | takes no argument and shall return either a string or preferably a tuple (the |
| 517 | returned object is often referred to as the "reduce value"). |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 518 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 519 | If a string is returned, the string should be interpreted as the name of a |
| 520 | global variable. It should be the object's local name relative to its |
| 521 | module; the pickle module searches the module namespace to determine the |
| 522 | object's module. This behaviour is typically useful for singletons. |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 523 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 524 | When a tuple is returned, it must be between two and five items long. |
| 525 | Optional items can either be omitted, or ``None`` can be provided as their |
| 526 | value. The semantics of each item are in order: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 527 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 528 | .. XXX Mention __newobj__ special-case? |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 529 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 530 | * A callable object that will be called to create the initial version of the |
| 531 | object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 532 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 533 | * A tuple of arguments for the callable object. An empty tuple must be given |
| 534 | if the callable does not accept any argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 535 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 536 | * Optionally, the object's state, which will be passed to the object's |
| 537 | :meth:`__setstate__` method as previously described. If the object has no |
| 538 | such method then, the value must be a dictionary and it will be added to |
| 539 | the object's :attr:`__dict__` attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 540 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 541 | * Optionally, an iterator (and not a sequence) yielding successive items. |
| 542 | These items will be appended to the object either using |
| 543 | ``obj.append(item)`` or, in batch, using ``obj.extend(list_of_items)``. |
| 544 | This is primarily used for list subclasses, but may be used by other |
| 545 | classes as long as they have :meth:`append` and :meth:`extend` methods with |
| 546 | the appropriate signature. (Whether :meth:`append` or :meth:`extend` is |
| 547 | used depends on which pickle protocol version is used as well as the number |
| 548 | of items to append, so both must be supported.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 549 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 550 | * Optionally, an iterator (not a sequence) yielding successive key-value |
| 551 | pairs. These items will be stored to the object using ``obj[key] = |
| 552 | value``. This is primarily used for dictionary subclasses, but may be used |
| 553 | by other classes as long as they implement :meth:`__setitem__`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 554 | |
Georg Brandl | c814826 | 2010-10-17 11:13:37 +0000 | [diff] [blame] | 555 | |
| 556 | .. method:: object.__reduce_ex__(protocol) |
| 557 | |
| 558 | Alternatively, a :meth:`__reduce_ex__` method may be defined. The only |
| 559 | difference is this method should take a single integer argument, the protocol |
| 560 | version. When defined, pickle will prefer it over the :meth:`__reduce__` |
| 561 | method. In addition, :meth:`__reduce__` automatically becomes a synonym for |
| 562 | the extended version. The main use for this method is to provide |
| 563 | backwards-compatible reduce values for older Python releases. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 564 | |
Alexandre Vassalotti | 758bca6 | 2008-10-18 19:25:07 +0000 | [diff] [blame] | 565 | .. _pickle-persistent: |
| 566 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 567 | Persistence of External Objects |
| 568 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 569 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 570 | .. index:: |
| 571 | single: persistent_id (pickle protocol) |
| 572 | single: persistent_load (pickle protocol) |
| 573 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 574 | For the benefit of object persistence, the :mod:`pickle` module supports the |
| 575 | notion of a reference to an object outside the pickled data stream. Such |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 576 | objects are referenced by a persistent ID, which should be either a string of |
| 577 | alphanumeric characters (for protocol 0) [#]_ or just an arbitrary object (for |
| 578 | any newer protocol). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 579 | |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 580 | The resolution of such persistent IDs is not defined by the :mod:`pickle` |
| 581 | module; it will delegate this resolution to the user defined methods on the |
| 582 | pickler and unpickler, :meth:`persistent_id` and :meth:`persistent_load` |
| 583 | respectively. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 584 | |
| 585 | To pickle objects that have an external persistent id, the pickler must have a |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 586 | custom :meth:`persistent_id` method that takes an object as an argument and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 587 | returns either ``None`` or the persistent id for that object. When ``None`` is |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 588 | returned, the pickler simply pickles the object as normal. When a persistent ID |
| 589 | string is returned, the pickler will pickle that object, along with a marker so |
| 590 | that the unpickler will recognize it as a persistent ID. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 591 | |
| 592 | To unpickle external objects, the unpickler must have a custom |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 593 | :meth:`persistent_load` method that takes a persistent ID object and returns the |
| 594 | referenced object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 595 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 596 | Here is a comprehensive example presenting how persistent ID can be used to |
| 597 | pickle external objects by reference. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 598 | |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 599 | .. literalinclude:: ../includes/dbpickle.py |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 600 | |
Antoine Pitrou | 8d3c290 | 2012-03-04 18:31:48 +0100 | [diff] [blame^] | 601 | .. _pickle-dispatch: |
| 602 | |
| 603 | Dispatch Tables |
| 604 | ^^^^^^^^^^^^^^^ |
| 605 | |
| 606 | If one wants to customize pickling of some classes without disturbing |
| 607 | any other code which depends on pickling, then one can create a |
| 608 | pickler with a private dispatch table. |
| 609 | |
| 610 | The global dispatch table managed by the :mod:`copyreg` module is |
| 611 | available as :data:`copyreg.dispatch_table`. Therefore, one may |
| 612 | choose to use a modified copy of :data:`copyreg.dispatch_table` as a |
| 613 | private dispatch table. |
| 614 | |
| 615 | For example :: |
| 616 | |
| 617 | f = io.BytesIO() |
| 618 | p = pickle.Pickler(f) |
| 619 | p.dispatch_table = copyreg.dispatch_table.copy() |
| 620 | p.dispatch_table[SomeClass] = reduce_SomeClass |
| 621 | |
| 622 | creates an instance of :class:`pickle.Pickler` with a private dispatch |
| 623 | table which handles the ``SomeClass`` class specially. Alternatively, |
| 624 | the code :: |
| 625 | |
| 626 | class MyPickler(pickle.Pickler): |
| 627 | dispatch_table = copyreg.dispatch_table.copy() |
| 628 | dispatch_table[SomeClass] = reduce_SomeClass |
| 629 | f = io.BytesIO() |
| 630 | p = MyPickler(f) |
| 631 | |
| 632 | does the same, but all instances of ``MyPickler`` will by default |
| 633 | share the same dispatch table. The equivalent code using the |
| 634 | :mod:`copyreg` module is :: |
| 635 | |
| 636 | copyreg.pickle(SomeClass, reduce_SomeClass) |
| 637 | f = io.BytesIO() |
| 638 | p = pickle.Pickler(f) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 639 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 640 | .. _pickle-state: |
| 641 | |
| 642 | Handling Stateful Objects |
| 643 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 644 | |
| 645 | .. index:: |
| 646 | single: __getstate__() (copy protocol) |
| 647 | single: __setstate__() (copy protocol) |
| 648 | |
| 649 | Here's an example that shows how to modify pickling behavior for a class. |
| 650 | The :class:`TextReader` class opens a text file, and returns the line number and |
| 651 | line contents each time its :meth:`readline` method is called. If a |
| 652 | :class:`TextReader` instance is pickled, all attributes *except* the file object |
| 653 | member are saved. When the instance is unpickled, the file is reopened, and |
| 654 | reading resumes from the last location. The :meth:`__setstate__` and |
| 655 | :meth:`__getstate__` methods are used to implement this behavior. :: |
| 656 | |
| 657 | class TextReader: |
| 658 | """Print and number lines in a text file.""" |
| 659 | |
| 660 | def __init__(self, filename): |
| 661 | self.filename = filename |
| 662 | self.file = open(filename) |
| 663 | self.lineno = 0 |
| 664 | |
| 665 | def readline(self): |
| 666 | self.lineno += 1 |
| 667 | line = self.file.readline() |
| 668 | if not line: |
| 669 | return None |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 670 | if line.endswith('\n'): |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 671 | line = line[:-1] |
| 672 | return "%i: %s" % (self.lineno, line) |
| 673 | |
| 674 | def __getstate__(self): |
| 675 | # Copy the object's state from self.__dict__ which contains |
| 676 | # all our instance attributes. Always use the dict.copy() |
| 677 | # method to avoid modifying the original state. |
| 678 | state = self.__dict__.copy() |
| 679 | # Remove the unpicklable entries. |
| 680 | del state['file'] |
| 681 | return state |
| 682 | |
| 683 | def __setstate__(self, state): |
| 684 | # Restore instance attributes (i.e., filename and lineno). |
| 685 | self.__dict__.update(state) |
| 686 | # Restore the previously opened file's state. To do so, we need to |
| 687 | # reopen it and read from it until the line count is restored. |
| 688 | file = open(self.filename) |
| 689 | for _ in range(self.lineno): |
| 690 | file.readline() |
| 691 | # Finally, save the file. |
| 692 | self.file = file |
| 693 | |
| 694 | |
| 695 | A sample usage might be something like this:: |
| 696 | |
| 697 | >>> reader = TextReader("hello.txt") |
| 698 | >>> reader.readline() |
| 699 | '1: Hello world!' |
| 700 | >>> reader.readline() |
| 701 | '2: I am line number two.' |
| 702 | >>> new_reader = pickle.loads(pickle.dumps(reader)) |
| 703 | >>> new_reader.readline() |
| 704 | '3: Goodbye!' |
| 705 | |
| 706 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 707 | .. _pickle-restrict: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 708 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 709 | Restricting Globals |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 710 | ------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 711 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 712 | .. index:: |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 713 | single: find_class() (pickle protocol) |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 714 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 715 | By default, unpickling will import any class or function that it finds in the |
| 716 | pickle data. For many applications, this behaviour is unacceptable as it |
| 717 | permits the unpickler to import and invoke arbitrary code. Just consider what |
| 718 | this hand-crafted pickle data stream does when loaded:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 719 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 720 | >>> import pickle |
| 721 | >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.") |
| 722 | hello world |
| 723 | 0 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 724 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 725 | In this example, the unpickler imports the :func:`os.system` function and then |
| 726 | apply the string argument "echo hello world". Although this example is |
| 727 | inoffensive, it is not difficult to imagine one that could damage your system. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 728 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 729 | For this reason, you may want to control what gets unpickled by customizing |
| 730 | :meth:`Unpickler.find_class`. Unlike its name suggests, :meth:`find_class` is |
| 731 | called whenever a global (i.e., a class or a function) is requested. Thus it is |
Ezio Melotti | e62aad3 | 2011-11-18 13:51:10 +0200 | [diff] [blame] | 732 | possible to either completely forbid globals or restrict them to a safe subset. |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 733 | |
| 734 | Here is an example of an unpickler allowing only few safe classes from the |
| 735 | :mod:`builtins` module to be loaded:: |
| 736 | |
| 737 | import builtins |
| 738 | import io |
| 739 | import pickle |
| 740 | |
| 741 | safe_builtins = { |
| 742 | 'range', |
| 743 | 'complex', |
| 744 | 'set', |
| 745 | 'frozenset', |
| 746 | 'slice', |
| 747 | } |
| 748 | |
| 749 | class RestrictedUnpickler(pickle.Unpickler): |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 750 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 751 | def find_class(self, module, name): |
| 752 | # Only allow safe classes from builtins. |
| 753 | if module == "builtins" and name in safe_builtins: |
| 754 | return getattr(builtins, name) |
| 755 | # Forbid everything else. |
| 756 | raise pickle.UnpicklingError("global '%s.%s' is forbidden" % |
| 757 | (module, name)) |
| 758 | |
| 759 | def restricted_loads(s): |
| 760 | """Helper function analogous to pickle.loads().""" |
| 761 | return RestrictedUnpickler(io.BytesIO(s)).load() |
| 762 | |
| 763 | A sample usage of our unpickler working has intended:: |
| 764 | |
| 765 | >>> restricted_loads(pickle.dumps([1, 2, range(15)])) |
| 766 | [1, 2, range(0, 15)] |
| 767 | >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.") |
| 768 | Traceback (most recent call last): |
| 769 | ... |
| 770 | pickle.UnpicklingError: global 'os.system' is forbidden |
| 771 | >>> restricted_loads(b'cbuiltins\neval\n' |
| 772 | ... b'(S\'getattr(__import__("os"), "system")' |
| 773 | ... b'("echo hello world")\'\ntR.') |
| 774 | Traceback (most recent call last): |
| 775 | ... |
| 776 | pickle.UnpicklingError: global 'builtins.eval' is forbidden |
| 777 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 778 | |
| 779 | .. XXX Add note about how extension codes could evade our protection |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 780 | mechanism (e.g. cached classes do not invokes find_class()). |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 781 | |
| 782 | As our examples shows, you have to be careful with what you allow to be |
| 783 | unpickled. Therefore if security is a concern, you may want to consider |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 784 | alternatives such as the marshalling API in :mod:`xmlrpc.client` or |
| 785 | third-party solutions. |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 786 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 787 | |
| 788 | .. _pickle-example: |
| 789 | |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 790 | Examples |
| 791 | -------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 792 | |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 793 | For the simplest code, use the :func:`dump` and :func:`load` functions. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 794 | |
| 795 | import pickle |
| 796 | |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 797 | # An arbitrary collection of objects supported by pickle. |
| 798 | data = { |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 799 | 'a': [1, 2.0, 3, 4+6j], |
| 800 | 'b': ("character string", b"byte string"), |
| 801 | 'c': set([None, True, False]) |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 802 | } |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 803 | |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 804 | with open('data.pickle', 'wb') as f: |
| 805 | # Pickle the 'data' dictionary using the highest protocol available. |
| 806 | pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 807 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 808 | |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 809 | The following example reads the resulting pickled data. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 810 | |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 811 | import pickle |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 812 | |
Alexandre Vassalotti | bcd1e3a | 2009-01-23 05:28:16 +0000 | [diff] [blame] | 813 | with open('data.pickle', 'rb') as f: |
| 814 | # The protocol version used is detected automatically, so we do not |
| 815 | # have to specify it. |
| 816 | data = pickle.load(f) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 817 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 818 | |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 819 | .. XXX: Add examples showing how to optimize pickles for size (like using |
| 820 | .. pickletools.optimize() or the gzip module). |
| 821 | |
| 822 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 823 | .. seealso:: |
| 824 | |
Alexandre Vassalotti | f7fa63d | 2008-05-11 08:55:36 +0000 | [diff] [blame] | 825 | Module :mod:`copyreg` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 826 | Pickle interface constructor registration for extension types. |
| 827 | |
Alexandre Vassalotti | 9d7665d | 2009-04-03 06:13:29 +0000 | [diff] [blame] | 828 | Module :mod:`pickletools` |
| 829 | Tools for working with and analyzing pickled data. |
| 830 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 831 | Module :mod:`shelve` |
| 832 | Indexed databases of objects; uses :mod:`pickle`. |
| 833 | |
| 834 | Module :mod:`copy` |
| 835 | Shallow and deep object copying. |
| 836 | |
| 837 | Module :mod:`marshal` |
| 838 | High-performance serialization of built-in types. |
| 839 | |
| 840 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 841 | .. rubric:: Footnotes |
| 842 | |
| 843 | .. [#] Don't confuse this with the :mod:`marshal` module |
| 844 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 845 | .. [#] The exception raised will likely be an :exc:`ImportError` or an |
| 846 | :exc:`AttributeError` but it could be something else. |
| 847 | |
Alexandre Vassalotti | 73b90a8 | 2008-10-29 23:32:33 +0000 | [diff] [blame] | 848 | .. [#] The :mod:`copy` module uses this protocol for shallow and deep copying |
| 849 | operations. |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 850 | |
Alexandre Vassalotti | d039286 | 2008-10-24 01:32:40 +0000 | [diff] [blame] | 851 | .. [#] The limitation on alphanumeric characters is due to the fact |
| 852 | the persistent IDs, in protocol 0, are delimited by the newline |
| 853 | character. Therefore if any kind of newline characters occurs in |
Alexandre Vassalotti | 5f3b63a | 2008-10-18 20:47:58 +0000 | [diff] [blame] | 854 | persistent IDs, the resulting pickle will become unreadable. |