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