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