blob: 52cbb6241bc9b96f413d9b93e785ec8dc61bef83 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`pickle` --- Python object serialization
2=============================================
3
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04004.. 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 Brandl116aa622007-08-15 14:28:22 +000012.. 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 Reedyfa089b92016-06-11 15:02:54 -040020--------------
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +000021
Antoine Pitroud4d60552013-12-07 00:56:59 +010022The :mod:`pickle` module implements binary protocols for serializing and
23de-serializing a Python object structure. *"Pickling"* is the process
24whereby 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
27back into an object hierarchy. Pickling (and unpickling) is alternatively
28known as "serialization", "marshalling," [#]_ or "flattening"; however, to
29avoid confusion, the terms used here are "pickling" and "unpickling".
Georg Brandl116aa622007-08-15 14:28:22 +000030
Georg Brandl0036bcf2010-10-17 10:24:54 +000031.. warning::
32
Benjamin Peterson7dcbf902015-07-06 11:28:07 -050033 The :mod:`pickle` module is not secure against erroneous or maliciously
Benjamin Petersonb8fd2622015-07-06 09:40:43 -050034 constructed data. Never unpickle data received from an untrusted or
35 unauthenticated source.
Georg Brandl0036bcf2010-10-17 10:24:54 +000036
Georg Brandl116aa622007-08-15 14:28:22 +000037
38Relationship to other Python modules
39------------------------------------
40
Antoine Pitroud4d60552013-12-07 00:56:59 +010041Comparison with ``marshal``
42^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +000043
44Python has a more primitive serialization module called :mod:`marshal`, but in
45general :mod:`pickle` should always be the preferred way to serialize Python
46objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc`
47files.
48
Georg Brandl5aa580f2010-11-30 14:57:54 +000049The :mod:`pickle` module differs from :mod:`marshal` in several significant ways:
Georg Brandl116aa622007-08-15 14:28:22 +000050
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 Pitroud4d60552013-12-07 00:56:59 +010076Comparison with ``json``
77^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +000078
Antoine Pitroud4d60552013-12-07 00:56:59 +010079There 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 Brandl116aa622007-08-15 14:28:22 +0000100
Antoine Pitrou9bcb1122013-12-07 01:05:57 +0100101
102.. _pickle-protocols:
103
Georg Brandl116aa622007-08-15 14:28:22 +0000104Data stream format
105------------------
106
107.. index::
Georg Brandl116aa622007-08-15 14:28:22 +0000108 single: External Data Representation
109
110The data format used by :mod:`pickle` is Python-specific. This has the
111advantage that there are no restrictions imposed by external standards such as
Antoine Pitroua9494f62012-05-10 15:38:30 +0200112JSON or XDR (which can't represent pointer sharing); however it means that
113non-Python programs may not be able to reconstruct pickled Python objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Antoine Pitroua9494f62012-05-10 15:38:30 +0200115By default, the :mod:`pickle` data format uses a relatively compact binary
116representation. If you need optimal size characteristics, you can efficiently
117:doc:`compress <archiving>` pickled data.
118
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000119The module :mod:`pickletools` contains tools for analyzing data streams
Antoine Pitroua9494f62012-05-10 15:38:30 +0200120generated by :mod:`pickle`. :mod:`pickletools` source code has extensive
121comments about opcodes used by pickle protocols.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Antoine Pitroub6457242014-01-21 02:39:54 +0100123There are currently 5 different protocols which can be used for pickling.
124The higher the protocol used, the more recent the version of Python needed
125to read the pickle produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Antoine Pitroua9494f62012-05-10 15:38:30 +0200127* Protocol version 0 is the original "human-readable" protocol and is
Alexandre Vassalottif7d08c72009-01-23 04:50:05 +0000128 backwards compatible with earlier versions of Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000129
Antoine Pitroua9494f62012-05-10 15:38:30 +0200130* Protocol version 1 is an old binary format which is also compatible with
Georg Brandl116aa622007-08-15 14:28:22 +0000131 earlier versions of Python.
132
133* Protocol version 2 was introduced in Python 2.3. It provides much more
Antoine Pitroua9494f62012-05-10 15:38:30 +0200134 efficient pickling of :term:`new-style class`\es. Refer to :pep:`307` for
135 information about improvements brought by protocol 2.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Antoine Pitrou9bcb1122013-12-07 01:05:57 +0100137* Protocol version 3 was added in Python 3.0. It has explicit support for
Antoine Pitroua9494f62012-05-10 15:38:30 +0200138 :class:`bytes` objects and cannot be unpickled by Python 2.x. This is
Antoine Pitrou9bcb1122013-12-07 01:05:57 +0100139 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 Brandl116aa622007-08-15 14:28:22 +0000146
Antoine Pitroud4d60552013-12-07 00:56:59 +0100147.. 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 Brandl116aa622007-08-15 14:28:22 +0000159
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000160Module Interface
161----------------
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Antoine Pitroua9494f62012-05-10 15:38:30 +0200163To serialize an object hierarchy, you simply call the :func:`dumps` function.
164Similarly, to de-serialize a data stream, you call the :func:`loads` function.
165However, if you want more control over serialization and de-serialization,
166you can create a :class:`Pickler` or an :class:`Unpickler` object, respectively.
167
168The :mod:`pickle` module provides the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170
171.. data:: HIGHEST_PROTOCOL
172
Antoine Pitrou9bcb1122013-12-07 01:05:57 +0100173 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 Brandl116aa622007-08-15 14:28:22 +0000177
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000178.. data:: DEFAULT_PROTOCOL
179
Antoine Pitrou9bcb1122013-12-07 01:05:57 +0100180 An integer, the default :ref:`protocol version <pickle-protocols>` used
181 for pickling. May be less than :data:`HIGHEST_PROTOCOL`. Currently the
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800182 default protocol is 3, a new protocol designed for Python 3.
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000183
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185The :mod:`pickle` module provides the following functions to make the pickling
186process more convenient:
187
Georg Brandl18244152009-09-02 20:34:52 +0000188.. function:: dump(obj, file, protocol=None, \*, fix_imports=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000190 Write a pickled representation of *obj* to the open :term:`file object` *file*.
191 This is equivalent to ``Pickler(file, protocol).dump(obj)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Antoine Pitroub6457242014-01-21 02:39:54 +0100193 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 Brandl116aa622007-08-15 14:28:22 +0000197
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000198 The *file* argument must have a write() method that accepts a single bytes
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200199 argument. It can thus be an on-disk file opened for binary writing, an
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000200 :class:`io.BytesIO` instance, or any other custom object that meets this
201 interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200203 If *fix_imports* is true and *protocol* is less than 3, pickle will try to
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800204 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 Pitroud9dfaa92009-06-04 20:32:06 +0000206
Georg Brandl18244152009-09-02 20:34:52 +0000207.. function:: dumps(obj, protocol=None, \*, fix_imports=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800209 Return the pickled representation of the object as a :class:`bytes` object,
210 instead of writing it to a file.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Antoine Pitroub6457242014-01-21 02:39:54 +0100212 Arguments *protocol* and *fix_imports* have the same meaning as in
213 :func:`dump`.
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000214
Georg Brandl18244152009-09-02 20:34:52 +0000215.. function:: load(file, \*, fix_imports=True, encoding="ASCII", errors="strict")
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000216
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800217 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 Vassalotti758bca62008-10-18 19:25:07 +0000220
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800221 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 Vassalotti758bca62008-10-18 19:25:07 +0000224
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 Vassalottid05c9ff2013-12-07 01:09:27 -0800227 methods should return bytes. Thus *file* can be an on-disk file opened for
Martin Panter7462b6492015-11-02 03:37:02 +0000228 binary reading, an :class:`io.BytesIO` object, or any other custom object
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000229 that meets this interface.
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000230
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000231 Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
Georg Brandl6faee4e2010-09-21 14:48:28 +0000232 which are used to control compatibility support for pickle stream generated
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800233 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 Pitroud9dfaa92009-06-04 20:32:06 +0000235 *errors* tell pickle how to decode 8-bit string instances pickled by Python
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800236 2; these default to 'ASCII' and 'strict', respectively. The *encoding* can
237 be 'bytes' to read these 8-bit string instances as bytes objects.
Serhiy Storchaka0d5730e2018-12-07 14:56:02 +0200238 Using ``encoding='latin1'`` is required for unpickling NumPy arrays and
239 instances of :class:`~datetime.datetime`, :class:`~datetime.date` and
240 :class:`~datetime.time` pickled by Python 2.
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000241
Georg Brandl18244152009-09-02 20:34:52 +0000242.. function:: loads(bytes_object, \*, fix_imports=True, encoding="ASCII", errors="strict")
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000243
244 Read a pickled object hierarchy from a :class:`bytes` object and return the
Martin Panterd21e0b52015-10-10 10:36:22 +0000245 reconstituted object hierarchy specified therein.
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000246
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800247 The protocol version of the pickle is detected automatically, so no
248 protocol argument is needed. Bytes past the pickled object's
249 representation are ignored.
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000250
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000251 Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
Georg Brandl6faee4e2010-09-21 14:48:28 +0000252 which are used to control compatibility support for pickle stream generated
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800253 by Python 2. If *fix_imports* is true, pickle will try to map the old
254 Python 2 names to the new names used in Python 3. The *encoding* and
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000255 *errors* tell pickle how to decode 8-bit string instances pickled by Python
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800256 2; these default to 'ASCII' and 'strict', respectively. The *encoding* can
257 be 'bytes' to read these 8-bit string instances as bytes objects.
Serhiy Storchaka0d5730e2018-12-07 14:56:02 +0200258 Using ``encoding='latin1'`` is required for unpickling NumPy arrays and
259 instances of :class:`~datetime.datetime`, :class:`~datetime.date` and
260 :class:`~datetime.time` pickled by Python 2.
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000263The :mod:`pickle` module defines three exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265.. exception:: PickleError
266
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000267 Common base class for the other pickling exceptions. It inherits
Georg Brandl116aa622007-08-15 14:28:22 +0000268 :exc:`Exception`.
269
Georg Brandl116aa622007-08-15 14:28:22 +0000270.. exception:: PicklingError
271
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000272 Error raised when an unpicklable object is encountered by :class:`Pickler`.
273 It inherits :exc:`PickleError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000275 Refer to :ref:`pickle-picklable` to learn what kinds of objects can be
276 pickled.
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278.. exception:: UnpicklingError
279
Ezio Melottie62aad32011-11-18 13:51:10 +0200280 Error raised when there is a problem unpickling an object, such as a data
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000281 corruption or a security violation. It inherits :exc:`PickleError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000283 Note that other exceptions may also be raised during unpickling, including
284 (but not necessarily limited to) AttributeError, EOFError, ImportError, and
285 IndexError.
286
287
288The :mod:`pickle` module exports two classes, :class:`Pickler` and
Georg Brandl116aa622007-08-15 14:28:22 +0000289:class:`Unpickler`:
290
Georg Brandl18244152009-09-02 20:34:52 +0000291.. class:: Pickler(file, protocol=None, \*, fix_imports=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000293 This takes a binary file for writing a pickle data stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Antoine Pitroub6457242014-01-21 02:39:54 +0100295 The optional *protocol* argument, an integer, tells the pickler to use
296 the given protocol; supported protocols are 0 to :data:`HIGHEST_PROTOCOL`.
297 If not specified, the default is :data:`DEFAULT_PROTOCOL`. If a negative
298 number is specified, :data:`HIGHEST_PROTOCOL` is selected.
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000300 The *file* argument must have a write() method that accepts a single bytes
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200301 argument. It can thus be an on-disk file opened for binary writing, an
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800302 :class:`io.BytesIO` instance, or any other custom object that meets this
303 interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200305 If *fix_imports* is true and *protocol* is less than 3, pickle will try to
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800306 map the new Python 3 names to the old module names used in Python 2, so
307 that the pickle data stream is readable with Python 2.
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000308
Benjamin Petersone41251e2008-04-25 01:59:09 +0000309 .. method:: dump(obj)
Georg Brandl116aa622007-08-15 14:28:22 +0000310
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000311 Write a pickled representation of *obj* to the open file object given in
312 the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000314 .. method:: persistent_id(obj)
315
316 Do nothing by default. This exists so a subclass can override it.
317
318 If :meth:`persistent_id` returns ``None``, *obj* is pickled as usual. Any
319 other value causes :class:`Pickler` to emit the returned value as a
320 persistent ID for *obj*. The meaning of this persistent ID should be
321 defined by :meth:`Unpickler.persistent_load`. Note that the value
322 returned by :meth:`persistent_id` cannot itself have a persistent ID.
323
324 See :ref:`pickle-persistent` for details and examples of uses.
Georg Brandl116aa622007-08-15 14:28:22 +0000325
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100326 .. attribute:: dispatch_table
327
328 A pickler object's dispatch table is a registry of *reduction
329 functions* of the kind which can be declared using
330 :func:`copyreg.pickle`. It is a mapping whose keys are classes
331 and whose values are reduction functions. A reduction function
332 takes a single argument of the associated class and should
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300333 conform to the same interface as a :meth:`__reduce__`
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100334 method.
335
336 By default, a pickler object will not have a
337 :attr:`dispatch_table` attribute, and it will instead use the
338 global dispatch table managed by the :mod:`copyreg` module.
339 However, to customize the pickling for a specific pickler object
340 one can set the :attr:`dispatch_table` attribute to a dict-like
341 object. Alternatively, if a subclass of :class:`Pickler` has a
342 :attr:`dispatch_table` attribute then this will be used as the
343 default dispatch table for instances of that class.
344
345 See :ref:`pickle-dispatch` for usage examples.
346
347 .. versionadded:: 3.3
348
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000349 .. attribute:: fast
350
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000351 Deprecated. Enable fast mode if set to a true value. The fast mode
352 disables the usage of memo, therefore speeding the pickling process by not
353 generating superfluous PUT opcodes. It should not be used with
354 self-referential objects, doing otherwise will cause :class:`Pickler` to
355 recurse infinitely.
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000356
357 Use :func:`pickletools.optimize` if you need more compact pickles.
358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Georg Brandl18244152009-09-02 20:34:52 +0000360.. class:: Unpickler(file, \*, fix_imports=True, encoding="ASCII", errors="strict")
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000362 This takes a binary file for reading a pickle data stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000364 The protocol version of the pickle is detected automatically, so no
365 protocol argument is needed.
366
367 The argument *file* must have two methods, a read() method that takes an
368 integer argument, and a readline() method that requires no arguments. Both
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800369 methods should return bytes. Thus *file* can be an on-disk file object
Martin Panter7462b6492015-11-02 03:37:02 +0000370 opened for binary reading, an :class:`io.BytesIO` object, or any other
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800371 custom object that meets this interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000373 Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
Georg Brandl6faee4e2010-09-21 14:48:28 +0000374 which are used to control compatibility support for pickle stream generated
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800375 by Python 2. If *fix_imports* is true, pickle will try to map the old
376 Python 2 names to the new names used in Python 3. The *encoding* and
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000377 *errors* tell pickle how to decode 8-bit string instances pickled by Python
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800378 2; these default to 'ASCII' and 'strict', respectively. The *encoding* can
Sebastian Pucilowskia8d25a12017-12-21 20:00:49 +1100379 be 'bytes' to read these 8-bit string instances as bytes objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Benjamin Petersone41251e2008-04-25 01:59:09 +0000381 .. method:: load()
Georg Brandl116aa622007-08-15 14:28:22 +0000382
Benjamin Petersone41251e2008-04-25 01:59:09 +0000383 Read a pickled object representation from the open file object given in
384 the constructor, and return the reconstituted object hierarchy specified
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000385 therein. Bytes past the pickled object's representation are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000387 .. method:: persistent_load(pid)
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Ezio Melottie62aad32011-11-18 13:51:10 +0200389 Raise an :exc:`UnpicklingError` by default.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000391 If defined, :meth:`persistent_load` should return the object specified by
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000392 the persistent ID *pid*. If an invalid persistent ID is encountered, an
Ezio Melottie62aad32011-11-18 13:51:10 +0200393 :exc:`UnpicklingError` should be raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000395 See :ref:`pickle-persistent` for details and examples of uses.
396
397 .. method:: find_class(module, name)
398
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000399 Import *module* if necessary and return the object called *name* from it,
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000400 where the *module* and *name* arguments are :class:`str` objects. Note,
401 unlike its name suggests, :meth:`find_class` is also used for finding
402 functions.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000404 Subclasses may override this to gain control over what type of objects and
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000405 how they can be loaded, potentially reducing security risks. Refer to
406 :ref:`pickle-restrict` for details.
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000407
408
409.. _pickle-picklable:
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411What can be pickled and unpickled?
412----------------------------------
413
414The following types can be pickled:
415
416* ``None``, ``True``, and ``False``
417
Georg Brandlba956ae2007-11-29 17:24:34 +0000418* integers, floating point numbers, complex numbers
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Georg Brandlf6945182008-02-01 11:56:49 +0000420* strings, bytes, bytearrays
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422* tuples, lists, sets, and dictionaries containing only picklable objects
423
Ethan Furman2498d9e2013-10-18 00:45:40 -0700424* functions defined at the top level of a module (using :keyword:`def`, not
425 :keyword:`lambda`)
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427* built-in functions defined at the top level of a module
428
429* classes that are defined at the top level of a module
430
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300431* instances of such classes whose :attr:`~object.__dict__` or the result of
432 calling :meth:`__getstate__` is picklable (see section :ref:`pickle-inst` for
Eli Bendersky78f3ce52013-01-02 05:53:59 -0800433 details).
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435Attempts to pickle unpicklable objects will raise the :exc:`PicklingError`
436exception; when this happens, an unspecified number of bytes may have already
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000437been written to the underlying file. Trying to pickle a highly recursive data
Yury Selivanovf488fb42015-07-03 01:04:23 -0400438structure may exceed the maximum recursion depth, a :exc:`RecursionError` will be
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000439raised in this case. You can carefully raise this limit with
Georg Brandl116aa622007-08-15 14:28:22 +0000440:func:`sys.setrecursionlimit`.
441
442Note that functions (built-in and user-defined) are pickled by "fully qualified"
Ethan Furman2498d9e2013-10-18 00:45:40 -0700443name reference, not by value. [#]_ This means that only the function name is
Eli Bendersky78f3ce52013-01-02 05:53:59 -0800444pickled, along with the name of the module the function is defined in. Neither
445the function's code, nor any of its function attributes are pickled. Thus the
Georg Brandl116aa622007-08-15 14:28:22 +0000446defining module must be importable in the unpickling environment, and the module
447must contain the named object, otherwise an exception will be raised. [#]_
448
449Similarly, classes are pickled by named reference, so the same restrictions in
450the unpickling environment apply. Note that none of the class's code or data is
451pickled, so in the following example the class attribute ``attr`` is not
452restored in the unpickling environment::
453
454 class Foo:
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000455 attr = 'A class attribute'
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457 picklestring = pickle.dumps(Foo)
458
459These restrictions are why picklable functions and classes must be defined in
460the top level of a module.
461
462Similarly, when class instances are pickled, their class's code and data are not
463pickled along with them. Only the instance data are pickled. This is done on
464purpose, so you can fix bugs in a class or add methods to the class and still
465load objects that were created with an earlier version of the class. If you
466plan to have long-lived objects that will see many versions of a class, it may
467be worthwhile to put a version number in the objects so that suitable
468conversions can be made by the class's :meth:`__setstate__` method.
469
470
Georg Brandl116aa622007-08-15 14:28:22 +0000471.. _pickle-inst:
472
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000473Pickling Class Instances
474------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000475
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300476.. currentmodule:: None
477
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000478In this section, we describe the general mechanisms available to you to define,
479customize, and control how class instances are pickled and unpickled.
Georg Brandl116aa622007-08-15 14:28:22 +0000480
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000481In most cases, no additional code is needed to make instances picklable. By
482default, pickle will retrieve the class and the attributes of an instance via
483introspection. When a class instance is unpickled, its :meth:`__init__` method
484is usually *not* invoked. The default behaviour first creates an uninitialized
485instance and then restores the saved attributes. The following code shows an
486implementation of this behaviour::
Georg Brandl85eb8c12007-08-31 16:33:38 +0000487
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000488 def save(obj):
489 return (obj.__class__, obj.__dict__)
490
491 def load(cls, attributes):
492 obj = cls.__new__(cls)
493 obj.__dict__.update(attributes)
494 return obj
Georg Brandl116aa622007-08-15 14:28:22 +0000495
Georg Brandl6faee4e2010-09-21 14:48:28 +0000496Classes can alter the default behaviour by providing one or several special
Georg Brandlc8148262010-10-17 11:13:37 +0000497methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000498
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100499.. method:: object.__getnewargs_ex__()
500
Serhiy Storchakab6d84832015-10-13 21:26:35 +0300501 In protocols 2 and newer, classes that implements the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100502 :meth:`__getnewargs_ex__` method can dictate the values passed to the
503 :meth:`__new__` method upon unpickling. The method must return a pair
504 ``(args, kwargs)`` where *args* is a tuple of positional arguments
505 and *kwargs* a dictionary of named arguments for constructing the
506 object. Those will be passed to the :meth:`__new__` method upon
507 unpickling.
508
509 You should implement this method if the :meth:`__new__` method of your
510 class requires keyword-only arguments. Otherwise, it is recommended for
511 compatibility to implement :meth:`__getnewargs__`.
512
Serhiy Storchakab6d84832015-10-13 21:26:35 +0300513 .. versionchanged:: 3.6
514 :meth:`__getnewargs_ex__` is now used in protocols 2 and 3.
515
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100516
Georg Brandlc8148262010-10-17 11:13:37 +0000517.. method:: object.__getnewargs__()
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Miss Islington (bot)92a58412018-06-09 18:01:36 -0700519 This method serves a similar purpose as :meth:`__getnewargs_ex__`, but
Serhiy Storchakab6d84832015-10-13 21:26:35 +0300520 supports only positional arguments. It must return a tuple of arguments
521 ``args`` which will be passed to the :meth:`__new__` method upon unpickling.
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100522
Serhiy Storchakab6d84832015-10-13 21:26:35 +0300523 :meth:`__getnewargs__` will not be called if :meth:`__getnewargs_ex__` is
524 defined.
525
526 .. versionchanged:: 3.6
527 Before Python 3.6, :meth:`__getnewargs__` was called instead of
528 :meth:`__getnewargs_ex__` in protocols 2 and 3.
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Georg Brandlc8148262010-10-17 11:13:37 +0000531.. method:: object.__getstate__()
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000532
Georg Brandlc8148262010-10-17 11:13:37 +0000533 Classes can further influence how their instances are pickled; if the class
534 defines the method :meth:`__getstate__`, it is called and the returned object
535 is pickled as the contents for the instance, instead of the contents of the
536 instance's dictionary. If the :meth:`__getstate__` method is absent, the
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300537 instance's :attr:`~object.__dict__` is pickled as usual.
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Georg Brandlc8148262010-10-17 11:13:37 +0000539
540.. method:: object.__setstate__(state)
541
542 Upon unpickling, if the class defines :meth:`__setstate__`, it is called with
543 the unpickled state. In that case, there is no requirement for the state
544 object to be a dictionary. Otherwise, the pickled state must be a dictionary
545 and its items are assigned to the new instance's dictionary.
546
547 .. note::
548
549 If :meth:`__getstate__` returns a false value, the :meth:`__setstate__`
550 method will not be called upon unpickling.
551
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000553Refer to the section :ref:`pickle-state` for more information about how to use
554the methods :meth:`__getstate__` and :meth:`__setstate__`.
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Benjamin Petersond23f8222009-04-05 19:13:16 +0000556.. note::
Georg Brandle720c0a2009-04-27 16:20:50 +0000557
Benjamin Petersond23f8222009-04-05 19:13:16 +0000558 At unpickling time, some methods like :meth:`__getattr__`,
559 :meth:`__getattribute__`, or :meth:`__setattr__` may be called upon the
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100560 instance. In case those methods rely on some internal invariant being
561 true, the type should implement :meth:`__getnewargs__` or
562 :meth:`__getnewargs_ex__` to establish such an invariant; otherwise,
563 neither :meth:`__new__` nor :meth:`__init__` will be called.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000564
Georg Brandlc8148262010-10-17 11:13:37 +0000565.. index:: pair: copy; protocol
Christian Heimes05e8be12008-02-23 18:30:17 +0000566
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000567As we shall see, pickle does not use directly the methods described above. In
568fact, these methods are part of the copy protocol which implements the
569:meth:`__reduce__` special method. The copy protocol provides a unified
570interface for retrieving the data necessary for pickling and copying
Georg Brandl48310cd2009-01-03 21:18:54 +0000571objects. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +0000572
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000573Although powerful, implementing :meth:`__reduce__` directly in your classes is
574error prone. For this reason, class designers should use the high-level
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100575interface (i.e., :meth:`__getnewargs_ex__`, :meth:`__getstate__` and
Georg Brandlc8148262010-10-17 11:13:37 +0000576:meth:`__setstate__`) whenever possible. We will show, however, cases where
577using :meth:`__reduce__` is the only option or leads to more efficient pickling
578or both.
Georg Brandl116aa622007-08-15 14:28:22 +0000579
Georg Brandlc8148262010-10-17 11:13:37 +0000580.. method:: object.__reduce__()
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000581
Georg Brandlc8148262010-10-17 11:13:37 +0000582 The interface is currently defined as follows. The :meth:`__reduce__` method
583 takes no argument and shall return either a string or preferably a tuple (the
584 returned object is often referred to as the "reduce value").
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000585
Georg Brandlc8148262010-10-17 11:13:37 +0000586 If a string is returned, the string should be interpreted as the name of a
587 global variable. It should be the object's local name relative to its
588 module; the pickle module searches the module namespace to determine the
589 object's module. This behaviour is typically useful for singletons.
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000590
Georg Brandlc8148262010-10-17 11:13:37 +0000591 When a tuple is returned, it must be between two and five items long.
592 Optional items can either be omitted, or ``None`` can be provided as their
593 value. The semantics of each item are in order:
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Georg Brandlc8148262010-10-17 11:13:37 +0000595 .. XXX Mention __newobj__ special-case?
Georg Brandl116aa622007-08-15 14:28:22 +0000596
Georg Brandlc8148262010-10-17 11:13:37 +0000597 * A callable object that will be called to create the initial version of the
598 object.
Georg Brandl116aa622007-08-15 14:28:22 +0000599
Georg Brandlc8148262010-10-17 11:13:37 +0000600 * A tuple of arguments for the callable object. An empty tuple must be given
601 if the callable does not accept any argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000602
Georg Brandlc8148262010-10-17 11:13:37 +0000603 * Optionally, the object's state, which will be passed to the object's
604 :meth:`__setstate__` method as previously described. If the object has no
605 such method then, the value must be a dictionary and it will be added to
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300606 the object's :attr:`~object.__dict__` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000607
Georg Brandlc8148262010-10-17 11:13:37 +0000608 * Optionally, an iterator (and not a sequence) yielding successive items.
609 These items will be appended to the object either using
610 ``obj.append(item)`` or, in batch, using ``obj.extend(list_of_items)``.
611 This is primarily used for list subclasses, but may be used by other
612 classes as long as they have :meth:`append` and :meth:`extend` methods with
613 the appropriate signature. (Whether :meth:`append` or :meth:`extend` is
614 used depends on which pickle protocol version is used as well as the number
615 of items to append, so both must be supported.)
Georg Brandl116aa622007-08-15 14:28:22 +0000616
Georg Brandlc8148262010-10-17 11:13:37 +0000617 * Optionally, an iterator (not a sequence) yielding successive key-value
618 pairs. These items will be stored to the object using ``obj[key] =
619 value``. This is primarily used for dictionary subclasses, but may be used
620 by other classes as long as they implement :meth:`__setitem__`.
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Georg Brandlc8148262010-10-17 11:13:37 +0000622
623.. method:: object.__reduce_ex__(protocol)
624
625 Alternatively, a :meth:`__reduce_ex__` method may be defined. The only
626 difference is this method should take a single integer argument, the protocol
627 version. When defined, pickle will prefer it over the :meth:`__reduce__`
628 method. In addition, :meth:`__reduce__` automatically becomes a synonym for
629 the extended version. The main use for this method is to provide
630 backwards-compatible reduce values for older Python releases.
Georg Brandl116aa622007-08-15 14:28:22 +0000631
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300632.. currentmodule:: pickle
633
Alexandre Vassalotti758bca62008-10-18 19:25:07 +0000634.. _pickle-persistent:
635
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000636Persistence of External Objects
637^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Christian Heimes05e8be12008-02-23 18:30:17 +0000639.. index::
640 single: persistent_id (pickle protocol)
641 single: persistent_load (pickle protocol)
642
Georg Brandl116aa622007-08-15 14:28:22 +0000643For the benefit of object persistence, the :mod:`pickle` module supports the
644notion of a reference to an object outside the pickled data stream. Such
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000645objects are referenced by a persistent ID, which should be either a string of
646alphanumeric characters (for protocol 0) [#]_ or just an arbitrary object (for
647any newer protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000649The resolution of such persistent IDs is not defined by the :mod:`pickle`
650module; it will delegate this resolution to the user defined methods on the
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300651pickler and unpickler, :meth:`~Pickler.persistent_id` and
652:meth:`~Unpickler.persistent_load` respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654To pickle objects that have an external persistent id, the pickler must have a
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300655custom :meth:`~Pickler.persistent_id` method that takes an object as an
656argument and returns either ``None`` or the persistent id for that object.
657When ``None`` is returned, the pickler simply pickles the object as normal.
658When a persistent ID string is returned, the pickler will pickle that object,
659along with a marker so that the unpickler will recognize it as a persistent ID.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661To unpickle external objects, the unpickler must have a custom
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300662:meth:`~Unpickler.persistent_load` method that takes a persistent ID object and
663returns the referenced object.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000665Here is a comprehensive example presenting how persistent ID can be used to
666pickle external objects by reference.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000668.. literalinclude:: ../includes/dbpickle.py
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000669
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100670.. _pickle-dispatch:
671
672Dispatch Tables
673^^^^^^^^^^^^^^^
674
675If one wants to customize pickling of some classes without disturbing
676any other code which depends on pickling, then one can create a
677pickler with a private dispatch table.
678
679The global dispatch table managed by the :mod:`copyreg` module is
680available as :data:`copyreg.dispatch_table`. Therefore, one may
681choose to use a modified copy of :data:`copyreg.dispatch_table` as a
682private dispatch table.
683
684For example ::
685
686 f = io.BytesIO()
687 p = pickle.Pickler(f)
688 p.dispatch_table = copyreg.dispatch_table.copy()
689 p.dispatch_table[SomeClass] = reduce_SomeClass
690
691creates an instance of :class:`pickle.Pickler` with a private dispatch
692table which handles the ``SomeClass`` class specially. Alternatively,
693the code ::
694
695 class MyPickler(pickle.Pickler):
696 dispatch_table = copyreg.dispatch_table.copy()
697 dispatch_table[SomeClass] = reduce_SomeClass
698 f = io.BytesIO()
699 p = MyPickler(f)
700
701does the same, but all instances of ``MyPickler`` will by default
702share the same dispatch table. The equivalent code using the
703:mod:`copyreg` module is ::
704
705 copyreg.pickle(SomeClass, reduce_SomeClass)
706 f = io.BytesIO()
707 p = pickle.Pickler(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000709.. _pickle-state:
710
711Handling Stateful Objects
712^^^^^^^^^^^^^^^^^^^^^^^^^
713
714.. index::
715 single: __getstate__() (copy protocol)
716 single: __setstate__() (copy protocol)
717
718Here's an example that shows how to modify pickling behavior for a class.
719The :class:`TextReader` class opens a text file, and returns the line number and
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300720line contents each time its :meth:`!readline` method is called. If a
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000721:class:`TextReader` instance is pickled, all attributes *except* the file object
722member are saved. When the instance is unpickled, the file is reopened, and
723reading resumes from the last location. The :meth:`__setstate__` and
724:meth:`__getstate__` methods are used to implement this behavior. ::
725
726 class TextReader:
727 """Print and number lines in a text file."""
728
729 def __init__(self, filename):
730 self.filename = filename
731 self.file = open(filename)
732 self.lineno = 0
733
734 def readline(self):
735 self.lineno += 1
736 line = self.file.readline()
737 if not line:
738 return None
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000739 if line.endswith('\n'):
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000740 line = line[:-1]
741 return "%i: %s" % (self.lineno, line)
742
743 def __getstate__(self):
744 # Copy the object's state from self.__dict__ which contains
745 # all our instance attributes. Always use the dict.copy()
746 # method to avoid modifying the original state.
747 state = self.__dict__.copy()
748 # Remove the unpicklable entries.
749 del state['file']
750 return state
751
752 def __setstate__(self, state):
753 # Restore instance attributes (i.e., filename and lineno).
754 self.__dict__.update(state)
755 # Restore the previously opened file's state. To do so, we need to
756 # reopen it and read from it until the line count is restored.
757 file = open(self.filename)
758 for _ in range(self.lineno):
759 file.readline()
760 # Finally, save the file.
761 self.file = file
762
763
764A sample usage might be something like this::
765
766 >>> reader = TextReader("hello.txt")
767 >>> reader.readline()
768 '1: Hello world!'
769 >>> reader.readline()
770 '2: I am line number two.'
771 >>> new_reader = pickle.loads(pickle.dumps(reader))
772 >>> new_reader.readline()
773 '3: Goodbye!'
774
775
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000776.. _pickle-restrict:
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000778Restricting Globals
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000779-------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Christian Heimes05e8be12008-02-23 18:30:17 +0000781.. index::
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000782 single: find_class() (pickle protocol)
Christian Heimes05e8be12008-02-23 18:30:17 +0000783
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000784By default, unpickling will import any class or function that it finds in the
785pickle data. For many applications, this behaviour is unacceptable as it
786permits the unpickler to import and invoke arbitrary code. Just consider what
787this hand-crafted pickle data stream does when loaded::
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000789 >>> import pickle
790 >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
791 hello world
792 0
Georg Brandl116aa622007-08-15 14:28:22 +0000793
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000794In this example, the unpickler imports the :func:`os.system` function and then
795apply the string argument "echo hello world". Although this example is
796inoffensive, it is not difficult to imagine one that could damage your system.
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000798For this reason, you may want to control what gets unpickled by customizing
Serhiy Storchaka5bbbc942013-10-14 10:43:46 +0300799:meth:`Unpickler.find_class`. Unlike its name suggests,
800:meth:`Unpickler.find_class` is called whenever a global (i.e., a class or
801a function) is requested. Thus it is possible to either completely forbid
802globals or restrict them to a safe subset.
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000803
804Here is an example of an unpickler allowing only few safe classes from the
805:mod:`builtins` module to be loaded::
806
807 import builtins
808 import io
809 import pickle
810
811 safe_builtins = {
812 'range',
813 'complex',
814 'set',
815 'frozenset',
816 'slice',
817 }
818
819 class RestrictedUnpickler(pickle.Unpickler):
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000820
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000821 def find_class(self, module, name):
822 # Only allow safe classes from builtins.
823 if module == "builtins" and name in safe_builtins:
824 return getattr(builtins, name)
825 # Forbid everything else.
826 raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
827 (module, name))
828
829 def restricted_loads(s):
830 """Helper function analogous to pickle.loads()."""
831 return RestrictedUnpickler(io.BytesIO(s)).load()
832
833A sample usage of our unpickler working has intended::
834
835 >>> restricted_loads(pickle.dumps([1, 2, range(15)]))
836 [1, 2, range(0, 15)]
837 >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
838 Traceback (most recent call last):
839 ...
840 pickle.UnpicklingError: global 'os.system' is forbidden
841 >>> restricted_loads(b'cbuiltins\neval\n'
842 ... b'(S\'getattr(__import__("os"), "system")'
843 ... b'("echo hello world")\'\ntR.')
844 Traceback (most recent call last):
845 ...
846 pickle.UnpicklingError: global 'builtins.eval' is forbidden
847
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000848
849.. XXX Add note about how extension codes could evade our protection
Georg Brandl48310cd2009-01-03 21:18:54 +0000850 mechanism (e.g. cached classes do not invokes find_class()).
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000851
852As our examples shows, you have to be careful with what you allow to be
853unpickled. Therefore if security is a concern, you may want to consider
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000854alternatives such as the marshalling API in :mod:`xmlrpc.client` or
855third-party solutions.
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000856
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Antoine Pitroud4d60552013-12-07 00:56:59 +0100858Performance
859-----------
860
861Recent versions of the pickle protocol (from protocol 2 and upwards) feature
862efficient binary encodings for several common features and built-in types.
863Also, the :mod:`pickle` module has a transparent optimizer written in C.
864
865
Georg Brandl116aa622007-08-15 14:28:22 +0000866.. _pickle-example:
867
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000868Examples
869--------
Georg Brandl116aa622007-08-15 14:28:22 +0000870
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000871For the simplest code, use the :func:`dump` and :func:`load` functions. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873 import pickle
874
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000875 # An arbitrary collection of objects supported by pickle.
876 data = {
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000877 'a': [1, 2.0, 3, 4+6j],
878 'b': ("character string", b"byte string"),
Raymond Hettingerdf1b6992014-11-09 15:56:33 -0800879 'c': {None, True, False}
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000880 }
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000882 with open('data.pickle', 'wb') as f:
883 # Pickle the 'data' dictionary using the highest protocol available.
884 pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000887The following example reads the resulting pickled data. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000888
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000889 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +0000890
Alexandre Vassalottibcd1e3a2009-01-23 05:28:16 +0000891 with open('data.pickle', 'rb') as f:
892 # The protocol version used is detected automatically, so we do not
893 # have to specify it.
894 data = pickle.load(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000897.. XXX: Add examples showing how to optimize pickles for size (like using
898.. pickletools.optimize() or the gzip module).
899
900
Georg Brandl116aa622007-08-15 14:28:22 +0000901.. seealso::
902
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000903 Module :mod:`copyreg`
Georg Brandl116aa622007-08-15 14:28:22 +0000904 Pickle interface constructor registration for extension types.
905
Alexandre Vassalotti9d7665d2009-04-03 06:13:29 +0000906 Module :mod:`pickletools`
907 Tools for working with and analyzing pickled data.
908
Georg Brandl116aa622007-08-15 14:28:22 +0000909 Module :mod:`shelve`
910 Indexed databases of objects; uses :mod:`pickle`.
911
912 Module :mod:`copy`
913 Shallow and deep object copying.
914
915 Module :mod:`marshal`
916 High-performance serialization of built-in types.
917
918
Georg Brandl116aa622007-08-15 14:28:22 +0000919.. rubric:: Footnotes
920
921.. [#] Don't confuse this with the :mod:`marshal` module
922
Ethan Furman2498d9e2013-10-18 00:45:40 -0700923.. [#] This is why :keyword:`lambda` functions cannot be pickled: all
924 :keyword:`lambda` functions share the same name: ``<lambda>``.
925
Georg Brandl116aa622007-08-15 14:28:22 +0000926.. [#] The exception raised will likely be an :exc:`ImportError` or an
927 :exc:`AttributeError` but it could be something else.
928
Alexandre Vassalotti73b90a82008-10-29 23:32:33 +0000929.. [#] The :mod:`copy` module uses this protocol for shallow and deep copying
930 operations.
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000931
Alexandre Vassalottid0392862008-10-24 01:32:40 +0000932.. [#] The limitation on alphanumeric characters is due to the fact
933 the persistent IDs, in protocol 0, are delimited by the newline
934 character. Therefore if any kind of newline characters occurs in
Alexandre Vassalotti5f3b63a2008-10-18 20:47:58 +0000935 persistent IDs, the resulting pickle will become unreadable.