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