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