1:mod:`!pickle` --- Python object serialization 2============================================== 3 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 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 20-------------- 21 22The :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". 30 31.. warning:: 32 33 The ``pickle`` module **is not secure**. Only unpickle data you trust. 34 35 It is possible to construct malicious pickle data which will **execute 36 arbitrary code during unpickling**. Never unpickle data that could have come 37 from an untrusted source, or that could have been tampered with. 38 39 Consider signing data with :mod:`hmac` if you need to ensure that it has not 40 been tampered with. 41 42 Safer serialization formats such as :mod:`json` may be more appropriate if 43 you are processing untrusted data. See :ref:`comparison-with-json`. 44 45 46Relationship to other Python modules 47------------------------------------ 48 49Comparison with ``marshal`` 50^^^^^^^^^^^^^^^^^^^^^^^^^^^ 51 52Python has a more primitive serialization module called :mod:`marshal`, but in 53general :mod:`pickle` should always be the preferred way to serialize Python 54objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc` 55files. 56 57The :mod:`pickle` module differs from :mod:`marshal` in several significant ways: 58 59* The :mod:`pickle` module keeps track of the objects it has already serialized, 60 so that later references to the same object won't be serialized again. 61 :mod:`marshal` doesn't do this. 62 63 This has implications both for recursive objects and object sharing. Recursive 64 objects are objects that contain references to themselves. These are not 65 handled by marshal, and in fact, attempting to marshal recursive objects will 66 crash your Python interpreter. Object sharing happens when there are multiple 67 references to the same object in different places in the object hierarchy being 68 serialized. :mod:`pickle` stores such objects only once, and ensures that all 69 other references point to the master copy. Shared objects remain shared, which 70 can be very important for mutable objects. 71 72* :mod:`marshal` cannot be used to serialize user-defined classes and their 73 instances. :mod:`pickle` can save and restore class instances transparently, 74 however the class definition must be importable and live in the same module as 75 when the object was stored. 76 77* The :mod:`marshal` serialization format is not guaranteed to be portable 78 across Python versions. Because its primary job in life is to support 79 :file:`.pyc` files, the Python implementers reserve the right to change the 80 serialization format in non-backwards compatible ways should the need arise. 81 The :mod:`pickle` serialization format is guaranteed to be backwards compatible 82 across Python releases provided a compatible pickle protocol is chosen and 83 pickling and unpickling code deals with Python 2 to Python 3 type differences 84 if your data is crossing that unique breaking change language boundary. 85 86 87.. _comparison-with-json: 88 89Comparison with ``json`` 90^^^^^^^^^^^^^^^^^^^^^^^^ 91 92There are fundamental differences between the pickle protocols and 93`JSON (JavaScript Object Notation) <https://json.org>`_: 94 95* JSON is a text serialization format (it outputs unicode text, although 96 most of the time it is then encoded to ``utf-8``), while pickle is 97 a binary serialization format; 98 99* JSON is human-readable, while pickle is not; 100 101* JSON is interoperable and widely used outside of the Python ecosystem, 102 while pickle is Python-specific; 103 104* JSON, by default, can only represent a subset of the Python built-in 105 types, and no custom classes; pickle can represent an extremely large 106 number of Python types (many of them automatically, by clever usage 107 of Python's introspection facilities; complex cases can be tackled by 108 implementing :ref:`specific object APIs <pickle-inst>`); 109 110* Unlike pickle, deserializing untrusted JSON does not in itself create an 111 arbitrary code execution vulnerability. 112 113.. seealso:: 114 The :mod:`json` module: a standard library module allowing JSON 115 serialization and deserialization. 116 117 118.. _pickle-protocols: 119 120Data stream format 121------------------ 122 123.. index:: 124 single: External Data Representation 125 126The data format used by :mod:`pickle` is Python-specific. This has the 127advantage that there are no restrictions imposed by external standards such as 128JSON (which can't represent pointer sharing); however it means that 129non-Python programs may not be able to reconstruct pickled Python objects. 130 131By default, the :mod:`pickle` data format uses a relatively compact binary 132representation. If you need optimal size characteristics, you can efficiently 133:doc:`compress <archiving>` pickled data. 134 135The module :mod:`pickletools` contains tools for analyzing data streams 136generated by :mod:`pickle`. :mod:`pickletools` source code has extensive 137comments about opcodes used by pickle protocols. 138 139There are currently 6 different protocols which can be used for pickling. 140The higher the protocol used, the more recent the version of Python needed 141to read the pickle produced. 142 143* Protocol version 0 is the original "human-readable" protocol and is 144 backwards compatible with earlier versions of Python. 145 146* Protocol version 1 is an old binary format which is also compatible with 147 earlier versions of Python. 148 149* Protocol version 2 was introduced in Python 2.3. It provides much more 150 efficient pickling of :term:`new-style classes <new-style class>`. Refer to :pep:`307` for 151 information about improvements brought by protocol 2. 152 153* Protocol version 3 was added in Python 3.0. It has explicit support for 154 :class:`bytes` objects and cannot be unpickled by Python 2.x. This was 155 the default protocol in Python 3.0--3.7. 156 157* Protocol version 4 was added in Python 3.4. It adds support for very large 158 objects, pickling more kinds of objects, and some data format 159 optimizations. It is the default protocol starting with Python 3.8. 160 Refer to :pep:`3154` for information about improvements brought by 161 protocol 4. 162 163* Protocol version 5 was added in Python 3.8. It adds support for out-of-band 164 data and speedup for in-band data. Refer to :pep:`574` for information about 165 improvements brought by protocol 5. 166 167.. note:: 168 Serialization is a more primitive notion than persistence; although 169 :mod:`pickle` reads and writes file objects, it does not handle the issue of 170 naming persistent objects, nor the (even more complicated) issue of concurrent 171 access to persistent objects. The :mod:`pickle` module can transform a complex 172 object into a byte stream and it can transform the byte stream into an object 173 with the same internal structure. Perhaps the most obvious thing to do with 174 these byte streams is to write them onto a file, but it is also conceivable to 175 send them across a network or store them in a database. The :mod:`shelve` 176 module provides a simple interface to pickle and unpickle objects on 177 DBM-style database files. 178 179 180Module Interface 181---------------- 182 183To serialize an object hierarchy, you simply call the :func:`dumps` function. 184Similarly, to de-serialize a data stream, you call the :func:`loads` function. 185However, if you want more control over serialization and de-serialization, 186you can create a :class:`Pickler` or an :class:`Unpickler` object, respectively. 187 188The :mod:`pickle` module provides the following constants: 189 190 191.. data:: HIGHEST_PROTOCOL 192 193 An integer, the highest :ref:`protocol version <pickle-protocols>` 194 available. This value can be passed as a *protocol* value to functions 195 :func:`dump` and :func:`dumps` as well as the :class:`Pickler` 196 constructor. 197 198.. data:: DEFAULT_PROTOCOL 199 200 An integer, the default :ref:`protocol version <pickle-protocols>` used 201 for pickling. May be less than :data:`HIGHEST_PROTOCOL`. Currently the 202 default protocol is 4, first introduced in Python 3.4 and incompatible 203 with previous versions. 204 205 .. versionchanged:: 3.0 206 207 The default protocol is 3. 208 209 .. versionchanged:: 3.8 210 211 The default protocol is 4. 212 213The :mod:`pickle` module provides the following functions to make the pickling 214process more convenient: 215 216.. function:: dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) 217 218 Write the pickled representation of the object *obj* to the open 219 :term:`file object` *file*. This is equivalent to 220 ``Pickler(file, protocol).dump(obj)``. 221 222 Arguments *file*, *protocol*, *fix_imports* and *buffer_callback* have 223 the same meaning as in the :class:`Pickler` constructor. 224 225 .. versionchanged:: 3.8 226 The *buffer_callback* argument was added. 227 228.. function:: dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None) 229 230 Return the pickled representation of the object *obj* as a :class:`bytes` object, 231 instead of writing it to a file. 232 233 Arguments *protocol*, *fix_imports* and *buffer_callback* have the same 234 meaning as in the :class:`Pickler` constructor. 235 236 .. versionchanged:: 3.8 237 The *buffer_callback* argument was added. 238 239.. function:: load(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) 240 241 Read the pickled representation of an object from the open :term:`file object` 242 *file* and return the reconstituted object hierarchy specified therein. 243 This is equivalent to ``Unpickler(file).load()``. 244 245 The protocol version of the pickle is detected automatically, so no 246 protocol argument is needed. Bytes past the pickled representation 247 of the object are ignored. 248 249 Arguments *file*, *fix_imports*, *encoding*, *errors*, *strict* and *buffers* 250 have the same meaning as in the :class:`Unpickler` constructor. 251 252 .. versionchanged:: 3.8 253 The *buffers* argument was added. 254 255.. function:: loads(data, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) 256 257 Return the reconstituted object hierarchy of the pickled representation 258 *data* of an object. *data* must be a :term:`bytes-like object`. 259 260 The protocol version of the pickle is detected automatically, so no 261 protocol argument is needed. Bytes past the pickled representation 262 of the object are ignored. 263 264 Arguments *fix_imports*, *encoding*, *errors*, *strict* and *buffers* 265 have the same meaning as in the :class:`Unpickler` constructor. 266 267 .. versionchanged:: 3.8 268 The *buffers* argument was added. 269 270 271The :mod:`pickle` module defines three exceptions: 272 273.. exception:: PickleError 274 275 Common base class for the other pickling exceptions. It inherits from 276 :exc:`Exception`. 277 278.. exception:: PicklingError 279 280 Error raised when an unpicklable object is encountered by :class:`Pickler`. 281 It inherits from :exc:`PickleError`. 282 283 Refer to :ref:`pickle-picklable` to learn what kinds of objects can be 284 pickled. 285 286.. exception:: UnpicklingError 287 288 Error raised when there is a problem unpickling an object, such as a data 289 corruption or a security violation. It inherits from :exc:`PickleError`. 290 291 Note that other exceptions may also be raised during unpickling, including 292 (but not necessarily limited to) AttributeError, EOFError, ImportError, and 293 IndexError. 294 295 296The :mod:`pickle` module exports three classes, :class:`Pickler`, 297:class:`Unpickler` and :class:`PickleBuffer`: 298 299.. class:: Pickler(file, protocol=None, *, fix_imports=True, buffer_callback=None) 300 301 This takes a binary file for writing a pickle data stream. 302 303 The optional *protocol* argument, an integer, tells the pickler to use 304 the given protocol; supported protocols are 0 to :data:`HIGHEST_PROTOCOL`. 305 If not specified, the default is :data:`DEFAULT_PROTOCOL`. If a negative 306 number is specified, :data:`HIGHEST_PROTOCOL` is selected. 307 308 The *file* argument must have a write() method that accepts a single bytes 309 argument. It can thus be an on-disk file opened for binary writing, an 310 :class:`io.BytesIO` instance, or any other custom object that meets this 311 interface. 312 313 If *fix_imports* is true and *protocol* is less than 3, pickle will try to 314 map the new Python 3 names to the old module names used in Python 2, so 315 that the pickle data stream is readable with Python 2. 316 317 If *buffer_callback* is ``None`` (the default), buffer views are 318 serialized into *file* as part of the pickle stream. 319 320 If *buffer_callback* is not ``None``, then it can be called any number 321 of times with a buffer view. If the callback returns a false value 322 (such as ``None``), the given buffer is :ref:`out-of-band <pickle-oob>`; 323 otherwise the buffer is serialized in-band, i.e. inside the pickle stream. 324 325 It is an error if *buffer_callback* is not ``None`` and *protocol* is 326 ``None`` or smaller than 5. 327 328 .. versionchanged:: 3.8 329 The *buffer_callback* argument was added. 330 331 .. method:: dump(obj) 332 333 Write the pickled representation of *obj* to the open file object given in 334 the constructor. 335 336 .. method:: persistent_id(obj) 337 338 Do nothing by default. This exists so a subclass can override it. 339 340 If :meth:`persistent_id` returns ``None``, *obj* is pickled as usual. Any 341 other value causes :class:`Pickler` to emit the returned value as a 342 persistent ID for *obj*. The meaning of this persistent ID should be 343 defined by :meth:`Unpickler.persistent_load`. Note that the value 344 returned by :meth:`persistent_id` cannot itself have a persistent ID. 345 346 See :ref:`pickle-persistent` for details and examples of uses. 347 348 .. versionchanged:: 3.13 349 Add the default implementation of this method in the C implementation 350 of :class:`!Pickler`. 351 352 .. attribute:: dispatch_table 353 354 A pickler object's dispatch table is a registry of *reduction 355 functions* of the kind which can be declared using 356 :func:`copyreg.pickle`. It is a mapping whose keys are classes 357 and whose values are reduction functions. A reduction function 358 takes a single argument of the associated class and should 359 conform to the same interface as a :meth:`~object.__reduce__` 360 method. 361 362 By default, a pickler object will not have a 363 :attr:`dispatch_table` attribute, and it will instead use the 364 global dispatch table managed by the :mod:`copyreg` module. 365 However, to customize the pickling for a specific pickler object 366 one can set the :attr:`dispatch_table` attribute to a dict-like 367 object. Alternatively, if a subclass of :class:`Pickler` has a 368 :attr:`dispatch_table` attribute then this will be used as the 369 default dispatch table for instances of that class. 370 371 See :ref:`pickle-dispatch` for usage examples. 372 373 .. versionadded:: 3.3 374 375 .. method:: reducer_override(obj) 376 377 Special reducer that can be defined in :class:`Pickler` subclasses. This 378 method has priority over any reducer in the :attr:`dispatch_table`. It 379 should conform to the same interface as a :meth:`~object.__reduce__` method, and 380 can optionally return :data:`NotImplemented` to fallback on 381 :attr:`dispatch_table`-registered reducers to pickle ``obj``. 382 383 For a detailed example, see :ref:`reducer_override`. 384 385 .. versionadded:: 3.8 386 387 .. attribute:: fast 388 389 Deprecated. Enable fast mode if set to a true value. The fast mode 390 disables the usage of memo, therefore speeding the pickling process by not 391 generating superfluous PUT opcodes. It should not be used with 392 self-referential objects, doing otherwise will cause :class:`Pickler` to 393 recurse infinitely. 394 395 Use :func:`pickletools.optimize` if you need more compact pickles. 396 397 398.. class:: Unpickler(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) 399 400 This takes a binary file for reading a pickle data stream. 401 402 The protocol version of the pickle is detected automatically, so no 403 protocol argument is needed. 404 405 The argument *file* must have three methods, a read() method that takes an 406 integer argument, a readinto() method that takes a buffer argument 407 and a readline() method that requires no arguments, as in the 408 :class:`io.BufferedIOBase` interface. Thus *file* can be an on-disk file 409 opened for binary reading, an :class:`io.BytesIO` object, or any other 410 custom object that meets this interface. 411 412 The optional arguments *fix_imports*, *encoding* and *errors* are used 413 to control compatibility support for pickle stream generated by Python 2. 414 If *fix_imports* is true, pickle will try to map the old Python 2 names 415 to the new names used in Python 3. The *encoding* and *errors* tell 416 pickle how to decode 8-bit string instances pickled by Python 2; 417 these default to 'ASCII' and 'strict', respectively. The *encoding* can 418 be 'bytes' to read these 8-bit string instances as bytes objects. 419 Using ``encoding='latin1'`` is required for unpickling NumPy arrays and 420 instances of :class:`~datetime.datetime`, :class:`~datetime.date` and 421 :class:`~datetime.time` pickled by Python 2. 422 423 If *buffers* is ``None`` (the default), then all data necessary for 424 deserialization must be contained in the pickle stream. This means 425 that the *buffer_callback* argument was ``None`` when a :class:`Pickler` 426 was instantiated (or when :func:`dump` or :func:`dumps` was called). 427 428 If *buffers* is not ``None``, it should be an iterable of buffer-enabled 429 objects that is consumed each time the pickle stream references 430 an :ref:`out-of-band <pickle-oob>` buffer view. Such buffers have been 431 given in order to the *buffer_callback* of a Pickler object. 432 433 .. versionchanged:: 3.8 434 The *buffers* argument was added. 435 436 .. method:: load() 437 438 Read the pickled representation of an object from the open file object 439 given in the constructor, and return the reconstituted object hierarchy 440 specified therein. Bytes past the pickled representation of the object 441 are ignored. 442 443 .. method:: persistent_load(pid) 444 445 Raise an :exc:`UnpicklingError` by default. 446 447 If defined, :meth:`persistent_load` should return the object specified by 448 the persistent ID *pid*. If an invalid persistent ID is encountered, an 449 :exc:`UnpicklingError` should be raised. 450 451 See :ref:`pickle-persistent` for details and examples of uses. 452 453 .. versionchanged:: 3.13 454 Add the default implementation of this method in the C implementation 455 of :class:`!Unpickler`. 456 457 .. method:: find_class(module, name) 458 459 Import *module* if necessary and return the object called *name* from it, 460 where the *module* and *name* arguments are :class:`str` objects. Note, 461 unlike its name suggests, :meth:`find_class` is also used for finding 462 functions. 463 464 Subclasses may override this to gain control over what type of objects and 465 how they can be loaded, potentially reducing security risks. Refer to 466 :ref:`pickle-restrict` for details. 467 468 .. audit-event:: pickle.find_class module,name pickle.Unpickler.find_class 469 470.. class:: PickleBuffer(buffer) 471 472 A wrapper for a buffer representing picklable data. *buffer* must be a 473 :ref:`buffer-providing <bufferobjects>` object, such as a 474 :term:`bytes-like object` or a N-dimensional array. 475 476 :class:`PickleBuffer` is itself a buffer provider, therefore it is 477 possible to pass it to other APIs expecting a buffer-providing object, 478 such as :class:`memoryview`. 479 480 :class:`PickleBuffer` objects can only be serialized using pickle 481 protocol 5 or higher. They are eligible for 482 :ref:`out-of-band serialization <pickle-oob>`. 483 484 .. versionadded:: 3.8 485 486 .. method:: raw() 487 488 Return a :class:`memoryview` of the memory area underlying this buffer. 489 The returned object is a one-dimensional, C-contiguous memoryview 490 with format ``B`` (unsigned bytes). :exc:`BufferError` is raised if 491 the buffer is neither C- nor Fortran-contiguous. 492 493 .. method:: release() 494 495 Release the underlying buffer exposed by the PickleBuffer object. 496 497 498.. _pickle-picklable: 499 500What can be pickled and unpickled? 501---------------------------------- 502 503The following types can be pickled: 504 505* built-in constants (``None``, ``True``, ``False``, ``Ellipsis``, and 506 :data:`NotImplemented`); 507 508* integers, floating-point numbers, complex numbers; 509 510* strings, bytes, bytearrays; 511 512* tuples, lists, sets, and dictionaries containing only picklable objects; 513 514* functions (built-in and user-defined) accessible from the top level of a 515 module (using :keyword:`def`, not :keyword:`lambda`); 516 517* classes accessible from the top level of a module; 518 519* instances of such classes whose the result of calling :meth:`~object.__getstate__` 520 is picklable (see section :ref:`pickle-inst` for details). 521 522Attempts to pickle unpicklable objects will raise the :exc:`PicklingError` 523exception; when this happens, an unspecified number of bytes may have already 524been written to the underlying file. Trying to pickle a highly recursive data 525structure may exceed the maximum recursion depth, a :exc:`RecursionError` will be 526raised in this case. You can carefully raise this limit with 527:func:`sys.setrecursionlimit`. 528 529Note that functions (built-in and user-defined) are pickled by fully 530:term:`qualified name`, not by value. [#]_ This means that only the function name is 531pickled, along with the name of the containing module and classes. Neither 532the function's code, nor any of its function attributes are pickled. Thus the 533defining module must be importable in the unpickling environment, and the module 534must contain the named object, otherwise an exception will be raised. [#]_ 535 536Similarly, classes are pickled by fully qualified name, so the same restrictions in 537the unpickling environment apply. Note that none of the class's code or data is 538pickled, so in the following example the class attribute ``attr`` is not 539restored in the unpickling environment:: 540 541 class Foo: 542 attr = 'A class attribute' 543 544 picklestring = pickle.dumps(Foo) 545 546These restrictions are why picklable functions and classes must be defined at 547the top level of a module. 548 549Similarly, when class instances are pickled, their class's code and data are not 550pickled along with them. Only the instance data are pickled. This is done on 551purpose, so you can fix bugs in a class or add methods to the class and still 552load objects that were created with an earlier version of the class. If you 553plan to have long-lived objects that will see many versions of a class, it may 554be worthwhile to put a version number in the objects so that suitable 555conversions can be made by the class's :meth:`~object.__setstate__` method. 556 557 558.. _pickle-inst: 559 560Pickling Class Instances 561------------------------ 562 563.. currentmodule:: None 564 565In this section, we describe the general mechanisms available to you to define, 566customize, and control how class instances are pickled and unpickled. 567 568In most cases, no additional code is needed to make instances picklable. By 569default, pickle will retrieve the class and the attributes of an instance via 570introspection. When a class instance is unpickled, its :meth:`~object.__init__` method 571is usually *not* invoked. The default behaviour first creates an uninitialized 572instance and then restores the saved attributes. The following code shows an 573implementation of this behaviour:: 574 575 def save(obj): 576 return (obj.__class__, obj.__dict__) 577 578 def restore(cls, attributes): 579 obj = cls.__new__(cls) 580 obj.__dict__.update(attributes) 581 return obj 582 583Classes can alter the default behaviour by providing one or several special 584methods: 585 586.. method:: object.__getnewargs_ex__() 587 588 In protocols 2 and newer, classes that implements the 589 :meth:`__getnewargs_ex__` method can dictate the values passed to the 590 :meth:`__new__` method upon unpickling. The method must return a pair 591 ``(args, kwargs)`` where *args* is a tuple of positional arguments 592 and *kwargs* a dictionary of named arguments for constructing the 593 object. Those will be passed to the :meth:`__new__` method upon 594 unpickling. 595 596 You should implement this method if the :meth:`__new__` method of your 597 class requires keyword-only arguments. Otherwise, it is recommended for 598 compatibility to implement :meth:`__getnewargs__`. 599 600 .. versionchanged:: 3.6 601 :meth:`__getnewargs_ex__` is now used in protocols 2 and 3. 602 603 604.. method:: object.__getnewargs__() 605 606 This method serves a similar purpose as :meth:`__getnewargs_ex__`, but 607 supports only positional arguments. It must return a tuple of arguments 608 ``args`` which will be passed to the :meth:`__new__` method upon unpickling. 609 610 :meth:`__getnewargs__` will not be called if :meth:`__getnewargs_ex__` is 611 defined. 612 613 .. versionchanged:: 3.6 614 Before Python 3.6, :meth:`__getnewargs__` was called instead of 615 :meth:`__getnewargs_ex__` in protocols 2 and 3. 616 617 618.. method:: object.__getstate__() 619 620 Classes can further influence how their instances are pickled by overriding 621 the method :meth:`__getstate__`. It is called and the returned object 622 is pickled as the contents for the instance, instead of a default state. 623 There are several cases: 624 625 * For a class that has no instance :attr:`~object.__dict__` and no 626 :attr:`~object.__slots__`, the default state is ``None``. 627 628 * For a class that has an instance :attr:`~object.__dict__` and no 629 :attr:`~object.__slots__`, the default state is ``self.__dict__``. 630 631 * For a class that has an instance :attr:`~object.__dict__` and 632 :attr:`~object.__slots__`, the default state is a tuple consisting of two 633 dictionaries: ``self.__dict__``, and a dictionary mapping slot 634 names to slot values. Only slots that have a value are 635 included in the latter. 636 637 * For a class that has :attr:`~object.__slots__` and no instance 638 :attr:`~object.__dict__`, the default state is a tuple whose first item 639 is ``None`` and whose second item is a dictionary mapping slot names 640 to slot values described in the previous bullet. 641 642 .. versionchanged:: 3.11 643 Added the default implementation of the ``__getstate__()`` method in the 644 :class:`object` class. 645 646 647.. method:: object.__setstate__(state) 648 649 Upon unpickling, if the class defines :meth:`__setstate__`, it is called with 650 the unpickled state. In that case, there is no requirement for the state 651 object to be a dictionary. Otherwise, the pickled state must be a dictionary 652 and its items are assigned to the new instance's dictionary. 653 654 .. note:: 655 656 If :meth:`__reduce__` returns a state with value ``None`` at pickling, 657 the :meth:`__setstate__` method will not be called upon unpickling. 658 659 660Refer to the section :ref:`pickle-state` for more information about how to use 661the methods :meth:`~object.__getstate__` and :meth:`~object.__setstate__`. 662 663.. note:: 664 665 At unpickling time, some methods like :meth:`~object.__getattr__`, 666 :meth:`~object.__getattribute__`, or :meth:`~object.__setattr__` may be called upon the 667 instance. In case those methods rely on some internal invariant being 668 true, the type should implement :meth:`~object.__new__` to establish such an 669 invariant, as :meth:`~object.__init__` is not called when unpickling an 670 instance. 671 672.. index:: pair: copy; protocol 673 674As we shall see, pickle does not use directly the methods described above. In 675fact, these methods are part of the copy protocol which implements the 676:meth:`~object.__reduce__` special method. The copy protocol provides a unified 677interface for retrieving the data necessary for pickling and copying 678objects. [#]_ 679 680Although powerful, implementing :meth:`~object.__reduce__` directly in your classes is 681error prone. For this reason, class designers should use the high-level 682interface (i.e., :meth:`~object.__getnewargs_ex__`, :meth:`~object.__getstate__` and 683:meth:`~object.__setstate__`) whenever possible. We will show, however, cases where 684using :meth:`!__reduce__` is the only option or leads to more efficient pickling 685or both. 686 687.. method:: object.__reduce__() 688 689 The interface is currently defined as follows. The :meth:`__reduce__` method 690 takes no argument and shall return either a string or preferably a tuple (the 691 returned object is often referred to as the "reduce value"). 692 693 If a string is returned, the string should be interpreted as the name of a 694 global variable. It should be the object's local name relative to its 695 module; the pickle module searches the module namespace to determine the 696 object's module. This behaviour is typically useful for singletons. 697 698 When a tuple is returned, it must be between two and six items long. 699 Optional items can either be omitted, or ``None`` can be provided as their 700 value. The semantics of each item are in order: 701 702 .. XXX Mention __newobj__ special-case? 703 704 * A callable object that will be called to create the initial version of the 705 object. 706 707 * A tuple of arguments for the callable object. An empty tuple must be given 708 if the callable does not accept any argument. 709 710 * Optionally, the object's state, which will be passed to the object's 711 :meth:`__setstate__` method as previously described. If the object has no 712 such method then, the value must be a dictionary and it will be added to 713 the object's :attr:`~object.__dict__` attribute. 714 715 * Optionally, an iterator (and not a sequence) yielding successive items. 716 These items will be appended to the object either using 717 ``obj.append(item)`` or, in batch, using ``obj.extend(list_of_items)``. 718 This is primarily used for list subclasses, but may be used by other 719 classes as long as they have 720 :ref:`append and extend methods <typesseq-common>` with 721 the appropriate signature. (Whether :meth:`!append` or :meth:`!extend` is 722 used depends on which pickle protocol version is used as well as the number 723 of items to append, so both must be supported.) 724 725 * Optionally, an iterator (not a sequence) yielding successive key-value 726 pairs. These items will be stored to the object using ``obj[key] = 727 value``. This is primarily used for dictionary subclasses, but may be used 728 by other classes as long as they implement :meth:`__setitem__`. 729 730 * Optionally, a callable with a ``(obj, state)`` signature. This 731 callable allows the user to programmatically control the state-updating 732 behavior of a specific object, instead of using ``obj``'s static 733 :meth:`__setstate__` method. If not ``None``, this callable will have 734 priority over ``obj``'s :meth:`__setstate__`. 735 736 .. versionadded:: 3.8 737 The optional sixth tuple item, ``(obj, state)``, was added. 738 739 740.. method:: object.__reduce_ex__(protocol) 741 742 Alternatively, a :meth:`__reduce_ex__` method may be defined. The only 743 difference is this method should take a single integer argument, the protocol 744 version. When defined, pickle will prefer it over the :meth:`__reduce__` 745 method. In addition, :meth:`__reduce__` automatically becomes a synonym for 746 the extended version. The main use for this method is to provide 747 backwards-compatible reduce values for older Python releases. 748 749.. currentmodule:: pickle 750 751.. _pickle-persistent: 752 753Persistence of External Objects 754^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 755 756.. index:: 757 single: persistent_id (pickle protocol) 758 single: persistent_load (pickle protocol) 759 760For the benefit of object persistence, the :mod:`pickle` module supports the 761notion of a reference to an object outside the pickled data stream. Such 762objects are referenced by a persistent ID, which should be either a string of 763alphanumeric characters (for protocol 0) [#]_ or just an arbitrary object (for 764any newer protocol). 765 766The resolution of such persistent IDs is not defined by the :mod:`pickle` 767module; it will delegate this resolution to the user-defined methods on the 768pickler and unpickler, :meth:`~Pickler.persistent_id` and 769:meth:`~Unpickler.persistent_load` respectively. 770 771To pickle objects that have an external persistent ID, the pickler must have a 772custom :meth:`~Pickler.persistent_id` method that takes an object as an 773argument and returns either ``None`` or the persistent ID for that object. 774When ``None`` is returned, the pickler simply pickles the object as normal. 775When a persistent ID string is returned, the pickler will pickle that object, 776along with a marker so that the unpickler will recognize it as a persistent ID. 777 778To unpickle external objects, the unpickler must have a custom 779:meth:`~Unpickler.persistent_load` method that takes a persistent ID object and 780returns the referenced object. 781 782Here is a comprehensive example presenting how persistent ID can be used to 783pickle external objects by reference. 784 785.. literalinclude:: ../includes/dbpickle.py 786 787.. _pickle-dispatch: 788 789Dispatch Tables 790^^^^^^^^^^^^^^^ 791 792If one wants to customize pickling of some classes without disturbing 793any other code which depends on pickling, then one can create a 794pickler with a private dispatch table. 795 796The global dispatch table managed by the :mod:`copyreg` module is 797available as :data:`!copyreg.dispatch_table`. Therefore, one may 798choose to use a modified copy of :data:`!copyreg.dispatch_table` as a 799private dispatch table. 800 801For example :: 802 803 f = io.BytesIO() 804 p = pickle.Pickler(f) 805 p.dispatch_table = copyreg.dispatch_table.copy() 806 p.dispatch_table[SomeClass] = reduce_SomeClass 807 808creates an instance of :class:`pickle.Pickler` with a private dispatch 809table which handles the ``SomeClass`` class specially. Alternatively, 810the code :: 811 812 class MyPickler(pickle.Pickler): 813 dispatch_table = copyreg.dispatch_table.copy() 814 dispatch_table[SomeClass] = reduce_SomeClass 815 f = io.BytesIO() 816 p = MyPickler(f) 817 818does the same but all instances of ``MyPickler`` will by default 819share the private dispatch table. On the other hand, the code :: 820 821 copyreg.pickle(SomeClass, reduce_SomeClass) 822 f = io.BytesIO() 823 p = pickle.Pickler(f) 824 825modifies the global dispatch table shared by all users of the :mod:`copyreg` module. 826 827.. _pickle-state: 828 829Handling Stateful Objects 830^^^^^^^^^^^^^^^^^^^^^^^^^ 831 832.. index:: 833 single: __getstate__() (copy protocol) 834 single: __setstate__() (copy protocol) 835 836Here's an example that shows how to modify pickling behavior for a class. 837The :class:`!TextReader` class below opens a text file, and returns the line number and 838line contents each time its :meth:`!readline` method is called. If a 839:class:`!TextReader` instance is pickled, all attributes *except* the file object 840member are saved. When the instance is unpickled, the file is reopened, and 841reading resumes from the last location. The :meth:`!__setstate__` and 842:meth:`!__getstate__` methods are used to implement this behavior. :: 843 844 class TextReader: 845 """Print and number lines in a text file.""" 846 847 def __init__(self, filename): 848 self.filename = filename 849 self.file = open(filename) 850 self.lineno = 0 851 852 def readline(self): 853 self.lineno += 1 854 line = self.file.readline() 855 if not line: 856 return None 857 if line.endswith('\n'): 858 line = line[:-1] 859 return "%i: %s" % (self.lineno, line) 860 861 def __getstate__(self): 862 # Copy the object's state from self.__dict__ which contains 863 # all our instance attributes. Always use the dict.copy() 864 # method to avoid modifying the original state. 865 state = self.__dict__.copy() 866 # Remove the unpicklable entries. 867 del state['file'] 868 return state 869 870 def __setstate__(self, state): 871 # Restore instance attributes (i.e., filename and lineno). 872 self.__dict__.update(state) 873 # Restore the previously opened file's state. To do so, we need to 874 # reopen it and read from it until the line count is restored. 875 file = open(self.filename) 876 for _ in range(self.lineno): 877 file.readline() 878 # Finally, save the file. 879 self.file = file 880 881 882A sample usage might be something like this:: 883 884 >>> reader = TextReader("hello.txt") 885 >>> reader.readline() 886 '1: Hello world!' 887 >>> reader.readline() 888 '2: I am line number two.' 889 >>> new_reader = pickle.loads(pickle.dumps(reader)) 890 >>> new_reader.readline() 891 '3: Goodbye!' 892 893.. _reducer_override: 894 895Custom Reduction for Types, Functions, and Other Objects 896-------------------------------------------------------- 897 898.. versionadded:: 3.8 899 900Sometimes, :attr:`~Pickler.dispatch_table` may not be flexible enough. 901In particular we may want to customize pickling based on another criterion 902than the object's type, or we may want to customize the pickling of 903functions and classes. 904 905For those cases, it is possible to subclass from the :class:`Pickler` class and 906implement a :meth:`~Pickler.reducer_override` method. This method can return an 907arbitrary reduction tuple (see :meth:`~object.__reduce__`). It can alternatively return 908:data:`NotImplemented` to fallback to the traditional behavior. 909 910If both the :attr:`~Pickler.dispatch_table` and 911:meth:`~Pickler.reducer_override` are defined, then 912:meth:`~Pickler.reducer_override` method takes priority. 913 914.. Note:: 915 For performance reasons, :meth:`~Pickler.reducer_override` may not be 916 called for the following objects: ``None``, ``True``, ``False``, and 917 exact instances of :class:`int`, :class:`float`, :class:`bytes`, 918 :class:`str`, :class:`dict`, :class:`set`, :class:`frozenset`, :class:`list` 919 and :class:`tuple`. 920 921Here is a simple example where we allow pickling and reconstructing 922a given class:: 923 924 import io 925 import pickle 926 927 class MyClass: 928 my_attribute = 1 929 930 class MyPickler(pickle.Pickler): 931 def reducer_override(self, obj): 932 """Custom reducer for MyClass.""" 933 if getattr(obj, "__name__", None) == "MyClass": 934 return type, (obj.__name__, obj.__bases__, 935 {'my_attribute': obj.my_attribute}) 936 else: 937 # For any other object, fallback to usual reduction 938 return NotImplemented 939 940 f = io.BytesIO() 941 p = MyPickler(f) 942 p.dump(MyClass) 943 944 del MyClass 945 946 unpickled_class = pickle.loads(f.getvalue()) 947 948 assert isinstance(unpickled_class, type) 949 assert unpickled_class.__name__ == "MyClass" 950 assert unpickled_class.my_attribute == 1 951 952 953.. _pickle-oob: 954 955Out-of-band Buffers 956------------------- 957 958.. versionadded:: 3.8 959 960In some contexts, the :mod:`pickle` module is used to transfer massive amounts 961of data. Therefore, it can be important to minimize the number of memory 962copies, to preserve performance and resource consumption. However, normal 963operation of the :mod:`pickle` module, as it transforms a graph-like structure 964of objects into a sequential stream of bytes, intrinsically involves copying 965data to and from the pickle stream. 966 967This constraint can be eschewed if both the *provider* (the implementation 968of the object types to be transferred) and the *consumer* (the implementation 969of the communications system) support the out-of-band transfer facilities 970provided by pickle protocol 5 and higher. 971 972Provider API 973^^^^^^^^^^^^ 974 975The large data objects to be pickled must implement a :meth:`~object.__reduce_ex__` 976method specialized for protocol 5 and higher, which returns a 977:class:`PickleBuffer` instance (instead of e.g. a :class:`bytes` object) 978for any large data. 979 980A :class:`PickleBuffer` object *signals* that the underlying buffer is 981eligible for out-of-band data transfer. Those objects remain compatible 982with normal usage of the :mod:`pickle` module. However, consumers can also 983opt-in to tell :mod:`pickle` that they will handle those buffers by 984themselves. 985 986Consumer API 987^^^^^^^^^^^^ 988 989A communications system can enable custom handling of the :class:`PickleBuffer` 990objects generated when serializing an object graph. 991 992On the sending side, it needs to pass a *buffer_callback* argument to 993:class:`Pickler` (or to the :func:`dump` or :func:`dumps` function), which 994will be called with each :class:`PickleBuffer` generated while pickling 995the object graph. Buffers accumulated by the *buffer_callback* will not 996see their data copied into the pickle stream, only a cheap marker will be 997inserted. 998 999On the receiving side, it needs to pass a *buffers* argument to 1000:class:`Unpickler` (or to the :func:`load` or :func:`loads` function), 1001which is an iterable of the buffers which were passed to *buffer_callback*. 1002That iterable should produce buffers in the same order as they were passed 1003to *buffer_callback*. Those buffers will provide the data expected by the 1004reconstructors of the objects whose pickling produced the original 1005:class:`PickleBuffer` objects. 1006 1007Between the sending side and the receiving side, the communications system 1008is free to implement its own transfer mechanism for out-of-band buffers. 1009Potential optimizations include the use of shared memory or datatype-dependent 1010compression. 1011 1012Example 1013^^^^^^^ 1014 1015Here is a trivial example where we implement a :class:`bytearray` subclass 1016able to participate in out-of-band buffer pickling:: 1017 1018 class ZeroCopyByteArray(bytearray): 1019 1020 def __reduce_ex__(self, protocol): 1021 if protocol >= 5: 1022 return type(self)._reconstruct, (PickleBuffer(self),), None 1023 else: 1024 # PickleBuffer is forbidden with pickle protocols <= 4. 1025 return type(self)._reconstruct, (bytearray(self),) 1026 1027 @classmethod 1028 def _reconstruct(cls, obj): 1029 with memoryview(obj) as m: 1030 # Get a handle over the original buffer object 1031 obj = m.obj 1032 if type(obj) is cls: 1033 # Original buffer object is a ZeroCopyByteArray, return it 1034 # as-is. 1035 return obj 1036 else: 1037 return cls(obj) 1038 1039The reconstructor (the ``_reconstruct`` class method) returns the buffer's 1040providing object if it has the right type. This is an easy way to simulate 1041zero-copy behaviour on this toy example. 1042 1043On the consumer side, we can pickle those objects the usual way, which 1044when unserialized will give us a copy of the original object:: 1045 1046 b = ZeroCopyByteArray(b"abc") 1047 data = pickle.dumps(b, protocol=5) 1048 new_b = pickle.loads(data) 1049 print(b == new_b) # True 1050 print(b is new_b) # False: a copy was made 1051 1052But if we pass a *buffer_callback* and then give back the accumulated 1053buffers when unserializing, we are able to get back the original object:: 1054 1055 b = ZeroCopyByteArray(b"abc") 1056 buffers = [] 1057 data = pickle.dumps(b, protocol=5, buffer_callback=buffers.append) 1058 new_b = pickle.loads(data, buffers=buffers) 1059 print(b == new_b) # True 1060 print(b is new_b) # True: no copy was made 1061 1062This example is limited by the fact that :class:`bytearray` allocates its 1063own memory: you cannot create a :class:`bytearray` instance that is backed 1064by another object's memory. However, third-party datatypes such as NumPy 1065arrays do not have this limitation, and allow use of zero-copy pickling 1066(or making as few copies as possible) when transferring between distinct 1067processes or systems. 1068 1069.. seealso:: :pep:`574` -- Pickle protocol 5 with out-of-band data 1070 1071 1072.. _pickle-restrict: 1073 1074Restricting Globals 1075------------------- 1076 1077.. index:: 1078 single: find_class() (pickle protocol) 1079 1080By default, unpickling will import any class or function that it finds in the 1081pickle data. For many applications, this behaviour is unacceptable as it 1082permits the unpickler to import and invoke arbitrary code. Just consider what 1083this hand-crafted pickle data stream does when loaded:: 1084 1085 >>> import pickle 1086 >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.") 1087 hello world 1088 0 1089 1090In this example, the unpickler imports the :func:`os.system` function and then 1091apply the string argument "echo hello world". Although this example is 1092inoffensive, it is not difficult to imagine one that could damage your system. 1093 1094For this reason, you may want to control what gets unpickled by customizing 1095:meth:`Unpickler.find_class`. Unlike its name suggests, 1096:meth:`Unpickler.find_class` is called whenever a global (i.e., a class or 1097a function) is requested. Thus it is possible to either completely forbid 1098globals or restrict them to a safe subset. 1099 1100Here is an example of an unpickler allowing only few safe classes from the 1101:mod:`builtins` module to be loaded:: 1102 1103 import builtins 1104 import io 1105 import pickle 1106 1107 safe_builtins = { 1108 'range', 1109 'complex', 1110 'set', 1111 'frozenset', 1112 'slice', 1113 } 1114 1115 class RestrictedUnpickler(pickle.Unpickler): 1116 1117 def find_class(self, module, name): 1118 # Only allow safe classes from builtins. 1119 if module == "builtins" and name in safe_builtins: 1120 return getattr(builtins, name) 1121 # Forbid everything else. 1122 raise pickle.UnpicklingError("global '%s.%s' is forbidden" % 1123 (module, name)) 1124 1125 def restricted_loads(s): 1126 """Helper function analogous to pickle.loads().""" 1127 return RestrictedUnpickler(io.BytesIO(s)).load() 1128 1129A sample usage of our unpickler working as intended:: 1130 1131 >>> restricted_loads(pickle.dumps([1, 2, range(15)])) 1132 [1, 2, range(0, 15)] 1133 >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.") 1134 Traceback (most recent call last): 1135 ... 1136 pickle.UnpicklingError: global 'os.system' is forbidden 1137 >>> restricted_loads(b'cbuiltins\neval\n' 1138 ... b'(S\'getattr(__import__("os"), "system")' 1139 ... b'("echo hello world")\'\ntR.') 1140 Traceback (most recent call last): 1141 ... 1142 pickle.UnpicklingError: global 'builtins.eval' is forbidden 1143 1144 1145.. XXX Add note about how extension codes could evade our protection 1146 mechanism (e.g. cached classes do not invokes find_class()). 1147 1148As our examples shows, you have to be careful with what you allow to be 1149unpickled. Therefore if security is a concern, you may want to consider 1150alternatives such as the marshalling API in :mod:`xmlrpc.client` or 1151third-party solutions. 1152 1153 1154Performance 1155----------- 1156 1157Recent versions of the pickle protocol (from protocol 2 and upwards) feature 1158efficient binary encodings for several common features and built-in types. 1159Also, the :mod:`pickle` module has a transparent optimizer written in C. 1160 1161 1162.. _pickle-example: 1163 1164Examples 1165-------- 1166 1167For the simplest code, use the :func:`dump` and :func:`load` functions. :: 1168 1169 import pickle 1170 1171 # An arbitrary collection of objects supported by pickle. 1172 data = { 1173 'a': [1, 2.0, 3+4j], 1174 'b': ("character string", b"byte string"), 1175 'c': {None, True, False} 1176 } 1177 1178 with open('data.pickle', 'wb') as f: 1179 # Pickle the 'data' dictionary using the highest protocol available. 1180 pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) 1181 1182 1183The following example reads the resulting pickled data. :: 1184 1185 import pickle 1186 1187 with open('data.pickle', 'rb') as f: 1188 # The protocol version used is detected automatically, so we do not 1189 # have to specify it. 1190 data = pickle.load(f) 1191 1192 1193.. XXX: Add examples showing how to optimize pickles for size (like using 1194.. pickletools.optimize() or the gzip module). 1195 1196 1197.. seealso:: 1198 1199 Module :mod:`copyreg` 1200 Pickle interface constructor registration for extension types. 1201 1202 Module :mod:`pickletools` 1203 Tools for working with and analyzing pickled data. 1204 1205 Module :mod:`shelve` 1206 Indexed databases of objects; uses :mod:`pickle`. 1207 1208 Module :mod:`copy` 1209 Shallow and deep object copying. 1210 1211 Module :mod:`marshal` 1212 High-performance serialization of built-in types. 1213 1214 1215.. rubric:: Footnotes 1216 1217.. [#] Don't confuse this with the :mod:`marshal` module 1218 1219.. [#] This is why :keyword:`lambda` functions cannot be pickled: all 1220 :keyword:`!lambda` functions share the same name: ``<lambda>``. 1221 1222.. [#] The exception raised will likely be an :exc:`ImportError` or an 1223 :exc:`AttributeError` but it could be something else. 1224 1225.. [#] The :mod:`copy` module uses this protocol for shallow and deep copying 1226 operations. 1227 1228.. [#] The limitation on alphanumeric characters is due to the fact 1229 that persistent IDs in protocol 0 are delimited by the newline 1230 character. Therefore if any kind of newline characters occurs in 1231 persistent IDs, the resulting pickled data will become unreadable. 1232