gooderp18绿色标准版
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1562 líneas
162KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="pickle — Python object serialization" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/pickle.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Source code: Lib/pickle.py The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Source code: Lib/pickle.py The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>pickle — Python object serialization &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="copyreg — Register pickle support functions" href="copyreg.html" />
  33. <link rel="prev" title="Data Persistence" href="persistence.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/pickle.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a><ul>
  86. <li><a class="reference internal" href="#relationship-to-other-python-modules">Relationship to other Python modules</a><ul>
  87. <li><a class="reference internal" href="#comparison-with-marshal">Comparison with <code class="docutils literal notranslate"><span class="pre">marshal</span></code></a></li>
  88. <li><a class="reference internal" href="#comparison-with-json">Comparison with <code class="docutils literal notranslate"><span class="pre">json</span></code></a></li>
  89. </ul>
  90. </li>
  91. <li><a class="reference internal" href="#data-stream-format">Data stream format</a></li>
  92. <li><a class="reference internal" href="#module-interface">Module Interface</a></li>
  93. <li><a class="reference internal" href="#what-can-be-pickled-and-unpickled">What can be pickled and unpickled?</a></li>
  94. <li><a class="reference internal" href="#pickling-class-instances">Pickling Class Instances</a><ul>
  95. <li><a class="reference internal" href="#persistence-of-external-objects">Persistence of External Objects</a></li>
  96. <li><a class="reference internal" href="#dispatch-tables">Dispatch Tables</a></li>
  97. <li><a class="reference internal" href="#handling-stateful-objects">Handling Stateful Objects</a></li>
  98. </ul>
  99. </li>
  100. <li><a class="reference internal" href="#custom-reduction-for-types-functions-and-other-objects">Custom Reduction for Types, Functions, and Other Objects</a></li>
  101. <li><a class="reference internal" href="#out-of-band-buffers">Out-of-band Buffers</a><ul>
  102. <li><a class="reference internal" href="#provider-api">Provider API</a></li>
  103. <li><a class="reference internal" href="#consumer-api">Consumer API</a></li>
  104. <li><a class="reference internal" href="#example">Example</a></li>
  105. </ul>
  106. </li>
  107. <li><a class="reference internal" href="#restricting-globals">Restricting Globals</a></li>
  108. <li><a class="reference internal" href="#performance">Performance</a></li>
  109. <li><a class="reference internal" href="#examples">Examples</a></li>
  110. </ul>
  111. </li>
  112. </ul>
  113. </div>
  114. <div>
  115. <h4>Previous topic</h4>
  116. <p class="topless"><a href="persistence.html"
  117. title="previous chapter">Data Persistence</a></p>
  118. </div>
  119. <div>
  120. <h4>Next topic</h4>
  121. <p class="topless"><a href="copyreg.html"
  122. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code> — Register <code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a></p>
  123. </div>
  124. <div role="note" aria-label="source link">
  125. <h3>This Page</h3>
  126. <ul class="this-page-menu">
  127. <li><a href="../bugs.html">Report a Bug</a></li>
  128. <li>
  129. <a href="https://github.com/python/cpython/blob/main/Doc/library/pickle.rst"
  130. rel="nofollow">Show Source
  131. </a>
  132. </li>
  133. </ul>
  134. </div>
  135. </nav>
  136. </div>
  137. </div>
  138. <div class="related" role="navigation" aria-label="related navigation">
  139. <h3>Navigation</h3>
  140. <ul>
  141. <li class="right" style="margin-right: 10px">
  142. <a href="../genindex.html" title="General Index"
  143. accesskey="I">index</a></li>
  144. <li class="right" >
  145. <a href="../py-modindex.html" title="Python Module Index"
  146. >modules</a> |</li>
  147. <li class="right" >
  148. <a href="copyreg.html" title="copyreg — Register pickle support functions"
  149. accesskey="N">next</a> |</li>
  150. <li class="right" >
  151. <a href="persistence.html" title="Data Persistence"
  152. accesskey="P">previous</a> |</li>
  153. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  154. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  155. <li class="switchers">
  156. <div class="language_switcher_placeholder"></div>
  157. <div class="version_switcher_placeholder"></div>
  158. </li>
  159. <li>
  160. </li>
  161. <li id="cpython-language-and-version">
  162. <a href="../index.html">3.12.3 Documentation</a> &#187;
  163. </li>
  164. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  165. <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">Data Persistence</a> &#187;</li>
  166. <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a></li>
  167. <li class="right">
  168. <div class="inline-search" role="search">
  169. <form class="inline-search" action="../search.html" method="get">
  170. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  171. <input type="submit" value="Go" />
  172. </form>
  173. </div>
  174. |
  175. </li>
  176. <li class="right">
  177. <label class="theme-selector-label">
  178. Theme
  179. <select class="theme-selector" oninput="activateTheme(this.value)">
  180. <option value="auto" selected>Auto</option>
  181. <option value="light">Light</option>
  182. <option value="dark">Dark</option>
  183. </select>
  184. </label> |</li>
  185. </ul>
  186. </div>
  187. <div class="document">
  188. <div class="documentwrapper">
  189. <div class="bodywrapper">
  190. <div class="body" role="main">
  191. <section id="module-pickle">
  192. <span id="pickle-python-object-serialization"></span><h1><a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> — Python object serialization<a class="headerlink" href="#module-pickle" title="Link to this heading">¶</a></h1>
  193. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/pickle.py">Lib/pickle.py</a></p>
  194. <hr class="docutils" id="index-0" />
  195. <p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module implements binary protocols for serializing and
  196. de-serializing a Python object structure. <em>“Pickling”</em> is the process
  197. whereby a Python object hierarchy is converted into a byte stream, and
  198. <em>“unpickling”</em> is the inverse operation, whereby a byte stream
  199. (from a <a class="reference internal" href="../glossary.html#term-binary-file"><span class="xref std std-term">binary file</span></a> or <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>) is converted
  200. back into an object hierarchy. Pickling (and unpickling) is alternatively
  201. known as “serialization”, “marshalling,” <a class="footnote-reference brackets" href="#id7" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a> or “flattening”; however, to
  202. avoid confusion, the terms used here are “pickling” and “unpickling”.</p>
  203. <div class="admonition warning">
  204. <p class="admonition-title">Warning</p>
  205. <p>The <code class="docutils literal notranslate"><span class="pre">pickle</span></code> module <strong>is not secure</strong>. Only unpickle data you trust.</p>
  206. <p>It is possible to construct malicious pickle data which will <strong>execute
  207. arbitrary code during unpickling</strong>. Never unpickle data that could have come
  208. from an untrusted source, or that could have been tampered with.</p>
  209. <p>Consider signing data with <a class="reference internal" href="hmac.html#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a> if you need to ensure that it has not
  210. been tampered with.</p>
  211. <p>Safer serialization formats such as <a class="reference internal" href="json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> may be more appropriate if
  212. you are processing untrusted data. See <a class="reference internal" href="#comparison-with-json"><span class="std std-ref">Comparison with json</span></a>.</p>
  213. </div>
  214. <section id="relationship-to-other-python-modules">
  215. <h2>Relationship to other Python modules<a class="headerlink" href="#relationship-to-other-python-modules" title="Link to this heading">¶</a></h2>
  216. <section id="comparison-with-marshal">
  217. <h3>Comparison with <code class="docutils literal notranslate"><span class="pre">marshal</span></code><a class="headerlink" href="#comparison-with-marshal" title="Link to this heading">¶</a></h3>
  218. <p>Python has a more primitive serialization module called <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a>, but in
  219. general <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> should always be the preferred way to serialize Python
  220. objects. <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> exists primarily to support Python’s <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code>
  221. files.</p>
  222. <p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module differs from <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> in several significant ways:</p>
  223. <ul>
  224. <li><p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module keeps track of the objects it has already serialized,
  225. so that later references to the same object won’t be serialized again.
  226. <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> doesn’t do this.</p>
  227. <p>This has implications both for recursive objects and object sharing. Recursive
  228. objects are objects that contain references to themselves. These are not
  229. handled by marshal, and in fact, attempting to marshal recursive objects will
  230. crash your Python interpreter. Object sharing happens when there are multiple
  231. references to the same object in different places in the object hierarchy being
  232. serialized. <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> stores such objects only once, and ensures that all
  233. other references point to the master copy. Shared objects remain shared, which
  234. can be very important for mutable objects.</p>
  235. </li>
  236. <li><p><a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> cannot be used to serialize user-defined classes and their
  237. instances. <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> can save and restore class instances transparently,
  238. however the class definition must be importable and live in the same module as
  239. when the object was stored.</p></li>
  240. <li><p>The <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> serialization format is not guaranteed to be portable
  241. across Python versions. Because its primary job in life is to support
  242. <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files, the Python implementers reserve the right to change the
  243. serialization format in non-backwards compatible ways should the need arise.
  244. The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> serialization format is guaranteed to be backwards compatible
  245. across Python releases provided a compatible pickle protocol is chosen and
  246. pickling and unpickling code deals with Python 2 to Python 3 type differences
  247. if your data is crossing that unique breaking change language boundary.</p></li>
  248. </ul>
  249. </section>
  250. <section id="comparison-with-json">
  251. <span id="id2"></span><h3>Comparison with <code class="docutils literal notranslate"><span class="pre">json</span></code><a class="headerlink" href="#comparison-with-json" title="Link to this heading">¶</a></h3>
  252. <p>There are fundamental differences between the pickle protocols and
  253. <a class="reference external" href="https://json.org">JSON (JavaScript Object Notation)</a>:</p>
  254. <ul class="simple">
  255. <li><p>JSON is a text serialization format (it outputs unicode text, although
  256. most of the time it is then encoded to <code class="docutils literal notranslate"><span class="pre">utf-8</span></code>), while pickle is
  257. a binary serialization format;</p></li>
  258. <li><p>JSON is human-readable, while pickle is not;</p></li>
  259. <li><p>JSON is interoperable and widely used outside of the Python ecosystem,
  260. while pickle is Python-specific;</p></li>
  261. <li><p>JSON, by default, can only represent a subset of the Python built-in
  262. types, and no custom classes; pickle can represent an extremely large
  263. number of Python types (many of them automatically, by clever usage
  264. of Python’s introspection facilities; complex cases can be tackled by
  265. implementing <a class="reference internal" href="#pickle-inst"><span class="std std-ref">specific object APIs</span></a>);</p></li>
  266. <li><p>Unlike pickle, deserializing untrusted JSON does not in itself create an
  267. arbitrary code execution vulnerability.</p></li>
  268. </ul>
  269. <div class="admonition seealso">
  270. <p class="admonition-title">See also</p>
  271. <p>The <a class="reference internal" href="json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module: a standard library module allowing JSON
  272. serialization and deserialization.</p>
  273. </div>
  274. </section>
  275. </section>
  276. <section id="data-stream-format">
  277. <span id="pickle-protocols"></span><h2>Data stream format<a class="headerlink" href="#data-stream-format" title="Link to this heading">¶</a></h2>
  278. <p id="index-1">The data format used by <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> is Python-specific. This has the
  279. advantage that there are no restrictions imposed by external standards such as
  280. JSON or XDR (which can’t represent pointer sharing); however it means that
  281. non-Python programs may not be able to reconstruct pickled Python objects.</p>
  282. <p>By default, the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> data format uses a relatively compact binary
  283. representation. If you need optimal size characteristics, you can efficiently
  284. <a class="reference internal" href="archiving.html"><span class="doc">compress</span></a> pickled data.</p>
  285. <p>The module <a class="reference internal" href="pickletools.html#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> contains tools for analyzing data streams
  286. generated by <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>. <a class="reference internal" href="pickletools.html#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> source code has extensive
  287. comments about opcodes used by pickle protocols.</p>
  288. <p>There are currently 6 different protocols which can be used for pickling.
  289. The higher the protocol used, the more recent the version of Python needed
  290. to read the pickle produced.</p>
  291. <ul class="simple">
  292. <li><p>Protocol version 0 is the original “human-readable” protocol and is
  293. backwards compatible with earlier versions of Python.</p></li>
  294. <li><p>Protocol version 1 is an old binary format which is also compatible with
  295. earlier versions of Python.</p></li>
  296. <li><p>Protocol version 2 was introduced in Python 2.3. It provides much more
  297. efficient pickling of <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style classes</span></a>. Refer to <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0307/"><strong>PEP 307</strong></a> for
  298. information about improvements brought by protocol 2.</p></li>
  299. <li><p>Protocol version 3 was added in Python 3.0. It has explicit support for
  300. <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects and cannot be unpickled by Python 2.x. This was
  301. the default protocol in Python 3.0–3.7.</p></li>
  302. <li><p>Protocol version 4 was added in Python 3.4. It adds support for very large
  303. objects, pickling more kinds of objects, and some data format
  304. optimizations. It is the default protocol starting with Python 3.8.
  305. Refer to <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-3154/"><strong>PEP 3154</strong></a> for information about improvements brought by
  306. protocol 4.</p></li>
  307. <li><p>Protocol version 5 was added in Python 3.8. It adds support for out-of-band
  308. data and speedup for in-band data. Refer to <span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0574/"><strong>PEP 574</strong></a> for information about
  309. improvements brought by protocol 5.</p></li>
  310. </ul>
  311. <div class="admonition note">
  312. <p class="admonition-title">Note</p>
  313. <p>Serialization is a more primitive notion than persistence; although
  314. <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> reads and writes file objects, it does not handle the issue of
  315. naming persistent objects, nor the (even more complicated) issue of concurrent
  316. access to persistent objects. The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module can transform a complex
  317. object into a byte stream and it can transform the byte stream into an object
  318. with the same internal structure. Perhaps the most obvious thing to do with
  319. these byte streams is to write them onto a file, but it is also conceivable to
  320. send them across a network or store them in a database. The <a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a>
  321. module provides a simple interface to pickle and unpickle objects on
  322. DBM-style database files.</p>
  323. </div>
  324. </section>
  325. <section id="module-interface">
  326. <h2>Module Interface<a class="headerlink" href="#module-interface" title="Link to this heading">¶</a></h2>
  327. <p>To serialize an object hierarchy, you simply call the <a class="reference internal" href="#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> function.
  328. Similarly, to de-serialize a data stream, you call the <a class="reference internal" href="#pickle.loads" title="pickle.loads"><code class="xref py py-func docutils literal notranslate"><span class="pre">loads()</span></code></a> function.
  329. However, if you want more control over serialization and de-serialization,
  330. you can create a <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> or an <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> object, respectively.</p>
  331. <p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module provides the following constants:</p>
  332. <dl class="py data">
  333. <dt class="sig sig-object py" id="pickle.HIGHEST_PROTOCOL">
  334. <span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">HIGHEST_PROTOCOL</span></span><a class="headerlink" href="#pickle.HIGHEST_PROTOCOL" title="Link to this definition">¶</a></dt>
  335. <dd><p>An integer, the highest <a class="reference internal" href="#pickle-protocols"><span class="std std-ref">protocol version</span></a>
  336. available. This value can be passed as a <em>protocol</em> value to functions
  337. <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a> and <a class="reference internal" href="#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> as well as the <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a>
  338. constructor.</p>
  339. </dd></dl>
  340. <dl class="py data">
  341. <dt class="sig sig-object py" id="pickle.DEFAULT_PROTOCOL">
  342. <span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">DEFAULT_PROTOCOL</span></span><a class="headerlink" href="#pickle.DEFAULT_PROTOCOL" title="Link to this definition">¶</a></dt>
  343. <dd><p>An integer, the default <a class="reference internal" href="#pickle-protocols"><span class="std std-ref">protocol version</span></a> used
  344. for pickling. May be less than <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-data docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a>. Currently the
  345. default protocol is 4, first introduced in Python 3.4 and incompatible
  346. with previous versions.</p>
  347. <div class="versionchanged">
  348. <p><span class="versionmodified changed">Changed in version 3.0: </span>The default protocol is 3.</p>
  349. </div>
  350. <div class="versionchanged">
  351. <p><span class="versionmodified changed">Changed in version 3.8: </span>The default protocol is 4.</p>
  352. </div>
  353. </dd></dl>
  354. <p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module provides the following functions to make the pickling
  355. process more convenient:</p>
  356. <dl class="py function">
  357. <dt class="sig sig-object py" id="pickle.dump">
  358. <span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">dump</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">file</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">protocol</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fix_imports</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.dump" title="Link to this definition">¶</a></dt>
  359. <dd><p>Write the pickled representation of the object <em>obj</em> to the open
  360. <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> <em>file</em>. This is equivalent to
  361. <code class="docutils literal notranslate"><span class="pre">Pickler(file,</span> <span class="pre">protocol).dump(obj)</span></code>.</p>
  362. <p>Arguments <em>file</em>, <em>protocol</em>, <em>fix_imports</em> and <em>buffer_callback</em> have
  363. the same meaning as in the <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> constructor.</p>
  364. <div class="versionchanged">
  365. <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>buffer_callback</em> argument was added.</p>
  366. </div>
  367. </dd></dl>
  368. <dl class="py function">
  369. <dt class="sig sig-object py" id="pickle.dumps">
  370. <span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">dumps</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">protocol</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fix_imports</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.dumps" title="Link to this definition">¶</a></dt>
  371. <dd><p>Return the pickled representation of the object <em>obj</em> as a <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> object,
  372. instead of writing it to a file.</p>
  373. <p>Arguments <em>protocol</em>, <em>fix_imports</em> and <em>buffer_callback</em> have the same
  374. meaning as in the <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> constructor.</p>
  375. <div class="versionchanged">
  376. <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>buffer_callback</em> argument was added.</p>
  377. </div>
  378. </dd></dl>
  379. <dl class="py function">
  380. <dt class="sig sig-object py" id="pickle.load">
  381. <span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">load</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">file</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fix_imports</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'ASCII'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'strict'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffers</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.load" title="Link to this definition">¶</a></dt>
  382. <dd><p>Read the pickled representation of an object from the open <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>
  383. <em>file</em> and return the reconstituted object hierarchy specified therein.
  384. This is equivalent to <code class="docutils literal notranslate"><span class="pre">Unpickler(file).load()</span></code>.</p>
  385. <p>The protocol version of the pickle is detected automatically, so no
  386. protocol argument is needed. Bytes past the pickled representation
  387. of the object are ignored.</p>
  388. <p>Arguments <em>file</em>, <em>fix_imports</em>, <em>encoding</em>, <em>errors</em>, <em>strict</em> and <em>buffers</em>
  389. have the same meaning as in the <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> constructor.</p>
  390. <div class="versionchanged">
  391. <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>buffers</em> argument was added.</p>
  392. </div>
  393. </dd></dl>
  394. <dl class="py function">
  395. <dt class="sig sig-object py" id="pickle.loads">
  396. <span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">loads</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">data</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">/</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fix_imports</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'ASCII'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'strict'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffers</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.loads" title="Link to this definition">¶</a></dt>
  397. <dd><p>Return the reconstituted object hierarchy of the pickled representation
  398. <em>data</em> of an object. <em>data</em> must be a <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>.</p>
  399. <p>The protocol version of the pickle is detected automatically, so no
  400. protocol argument is needed. Bytes past the pickled representation
  401. of the object are ignored.</p>
  402. <p>Arguments <em>fix_imports</em>, <em>encoding</em>, <em>errors</em>, <em>strict</em> and <em>buffers</em>
  403. have the same meaning as in the <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> constructor.</p>
  404. <div class="versionchanged">
  405. <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>buffers</em> argument was added.</p>
  406. </div>
  407. </dd></dl>
  408. <p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module defines three exceptions:</p>
  409. <dl class="py exception">
  410. <dt class="sig sig-object py" id="pickle.PickleError">
  411. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">PickleError</span></span><a class="headerlink" href="#pickle.PickleError" title="Link to this definition">¶</a></dt>
  412. <dd><p>Common base class for the other pickling exceptions. It inherits from
  413. <a class="reference internal" href="exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p>
  414. </dd></dl>
  415. <dl class="py exception">
  416. <dt class="sig sig-object py" id="pickle.PicklingError">
  417. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">PicklingError</span></span><a class="headerlink" href="#pickle.PicklingError" title="Link to this definition">¶</a></dt>
  418. <dd><p>Error raised when an unpicklable object is encountered by <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a>.
  419. It inherits from <a class="reference internal" href="#pickle.PickleError" title="pickle.PickleError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PickleError</span></code></a>.</p>
  420. <p>Refer to <a class="reference internal" href="#pickle-picklable"><span class="std std-ref">What can be pickled and unpickled?</span></a> to learn what kinds of objects can be
  421. pickled.</p>
  422. </dd></dl>
  423. <dl class="py exception">
  424. <dt class="sig sig-object py" id="pickle.UnpicklingError">
  425. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">UnpicklingError</span></span><a class="headerlink" href="#pickle.UnpicklingError" title="Link to this definition">¶</a></dt>
  426. <dd><p>Error raised when there is a problem unpickling an object, such as a data
  427. corruption or a security violation. It inherits from <a class="reference internal" href="#pickle.PickleError" title="pickle.PickleError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PickleError</span></code></a>.</p>
  428. <p>Note that other exceptions may also be raised during unpickling, including
  429. (but not necessarily limited to) AttributeError, EOFError, ImportError, and
  430. IndexError.</p>
  431. </dd></dl>
  432. <p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module exports three classes, <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a>,
  433. <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> and <a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a>:</p>
  434. <dl class="py class">
  435. <dt class="sig sig-object py" id="pickle.Pickler">
  436. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">Pickler</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">file</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">protocol</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fix_imports</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler" title="Link to this definition">¶</a></dt>
  437. <dd><p>This takes a binary file for writing a pickle data stream.</p>
  438. <p>The optional <em>protocol</em> argument, an integer, tells the pickler to use
  439. the given protocol; supported protocols are 0 to <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-data docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a>.
  440. If not specified, the default is <a class="reference internal" href="#pickle.DEFAULT_PROTOCOL" title="pickle.DEFAULT_PROTOCOL"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT_PROTOCOL</span></code></a>. If a negative
  441. number is specified, <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-data docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a> is selected.</p>
  442. <p>The <em>file</em> argument must have a write() method that accepts a single bytes
  443. argument. It can thus be an on-disk file opened for binary writing, an
  444. <a class="reference internal" href="io.html#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BytesIO</span></code></a> instance, or any other custom object that meets this
  445. interface.</p>
  446. <p>If <em>fix_imports</em> is true and <em>protocol</em> is less than 3, pickle will try to
  447. map the new Python 3 names to the old module names used in Python 2, so
  448. that the pickle data stream is readable with Python 2.</p>
  449. <p>If <em>buffer_callback</em> is None (the default), buffer views are
  450. serialized into <em>file</em> as part of the pickle stream.</p>
  451. <p>If <em>buffer_callback</em> is not None, then it can be called any number
  452. of times with a buffer view. If the callback returns a false value
  453. (such as None), the given buffer is <a class="reference internal" href="#pickle-oob"><span class="std std-ref">out-of-band</span></a>;
  454. otherwise the buffer is serialized in-band, i.e. inside the pickle stream.</p>
  455. <p>It is an error if <em>buffer_callback</em> is not None and <em>protocol</em> is
  456. None or smaller than 5.</p>
  457. <div class="versionchanged">
  458. <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>buffer_callback</em> argument was added.</p>
  459. </div>
  460. <dl class="py method">
  461. <dt class="sig sig-object py" id="pickle.Pickler.dump">
  462. <span class="sig-name descname"><span class="pre">dump</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler.dump" title="Link to this definition">¶</a></dt>
  463. <dd><p>Write the pickled representation of <em>obj</em> to the open file object given in
  464. the constructor.</p>
  465. </dd></dl>
  466. <dl class="py method">
  467. <dt class="sig sig-object py" id="pickle.Pickler.persistent_id">
  468. <span class="sig-name descname"><span class="pre">persistent_id</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler.persistent_id" title="Link to this definition">¶</a></dt>
  469. <dd><p>Do nothing by default. This exists so a subclass can override it.</p>
  470. <p>If <a class="reference internal" href="#pickle.Pickler.persistent_id" title="pickle.Pickler.persistent_id"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_id()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>obj</em> is pickled as usual. Any
  471. other value causes <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> to emit the returned value as a
  472. persistent ID for <em>obj</em>. The meaning of this persistent ID should be
  473. defined by <a class="reference internal" href="#pickle.Unpickler.persistent_load" title="pickle.Unpickler.persistent_load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Unpickler.persistent_load()</span></code></a>. Note that the value
  474. returned by <a class="reference internal" href="#pickle.Pickler.persistent_id" title="pickle.Pickler.persistent_id"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_id()</span></code></a> cannot itself have a persistent ID.</p>
  475. <p>See <a class="reference internal" href="#pickle-persistent"><span class="std std-ref">Persistence of External Objects</span></a> for details and examples of uses.</p>
  476. </dd></dl>
  477. <dl class="py attribute">
  478. <dt class="sig sig-object py" id="pickle.Pickler.dispatch_table">
  479. <span class="sig-name descname"><span class="pre">dispatch_table</span></span><a class="headerlink" href="#pickle.Pickler.dispatch_table" title="Link to this definition">¶</a></dt>
  480. <dd><p>A pickler object’s dispatch table is a registry of <em>reduction
  481. functions</em> of the kind which can be declared using
  482. <a class="reference internal" href="copyreg.html#copyreg.pickle" title="copyreg.pickle"><code class="xref py py-func docutils literal notranslate"><span class="pre">copyreg.pickle()</span></code></a>. It is a mapping whose keys are classes
  483. and whose values are reduction functions. A reduction function
  484. takes a single argument of the associated class and should
  485. conform to the same interface as a <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>
  486. method.</p>
  487. <p>By default, a pickler object will not have a
  488. <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a> attribute, and it will instead use the
  489. global dispatch table managed by the <a class="reference internal" href="copyreg.html#module-copyreg" title="copyreg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code></a> module.
  490. However, to customize the pickling for a specific pickler object
  491. one can set the <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a> attribute to a dict-like
  492. object. Alternatively, if a subclass of <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> has a
  493. <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a> attribute then this will be used as the
  494. default dispatch table for instances of that class.</p>
  495. <p>See <a class="reference internal" href="#pickle-dispatch"><span class="std std-ref">Dispatch Tables</span></a> for usage examples.</p>
  496. <div class="versionadded">
  497. <p><span class="versionmodified added">New in version 3.3.</span></p>
  498. </div>
  499. </dd></dl>
  500. <dl class="py method">
  501. <dt class="sig sig-object py" id="pickle.Pickler.reducer_override">
  502. <span class="sig-name descname"><span class="pre">reducer_override</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">obj</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler.reducer_override" title="Link to this definition">¶</a></dt>
  503. <dd><p>Special reducer that can be defined in <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> subclasses. This
  504. method has priority over any reducer in the <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a>. It
  505. should conform to the same interface as a <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method, and
  506. can optionally return <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> to fallback on
  507. <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a>-registered reducers to pickle <code class="docutils literal notranslate"><span class="pre">obj</span></code>.</p>
  508. <p>For a detailed example, see <a class="reference internal" href="#reducer-override"><span class="std std-ref">Custom Reduction for Types, Functions, and Other Objects</span></a>.</p>
  509. <div class="versionadded">
  510. <p><span class="versionmodified added">New in version 3.8.</span></p>
  511. </div>
  512. </dd></dl>
  513. <dl class="py attribute">
  514. <dt class="sig sig-object py" id="pickle.Pickler.fast">
  515. <span class="sig-name descname"><span class="pre">fast</span></span><a class="headerlink" href="#pickle.Pickler.fast" title="Link to this definition">¶</a></dt>
  516. <dd><p>Deprecated. Enable fast mode if set to a true value. The fast mode
  517. disables the usage of memo, therefore speeding the pickling process by not
  518. generating superfluous PUT opcodes. It should not be used with
  519. self-referential objects, doing otherwise will cause <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> to
  520. recurse infinitely.</p>
  521. <p>Use <a class="reference internal" href="pickletools.html#pickletools.optimize" title="pickletools.optimize"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickletools.optimize()</span></code></a> if you need more compact pickles.</p>
  522. </dd></dl>
  523. </dd></dl>
  524. <dl class="py class">
  525. <dt class="sig sig-object py" id="pickle.Unpickler">
  526. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">Unpickler</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">file</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">fix_imports</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'ASCII'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'strict'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffers</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler" title="Link to this definition">¶</a></dt>
  527. <dd><p>This takes a binary file for reading a pickle data stream.</p>
  528. <p>The protocol version of the pickle is detected automatically, so no
  529. protocol argument is needed.</p>
  530. <p>The argument <em>file</em> must have three methods, a read() method that takes an
  531. integer argument, a readinto() method that takes a buffer argument
  532. and a readline() method that requires no arguments, as in the
  533. <a class="reference internal" href="io.html#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BufferedIOBase</span></code></a> interface. Thus <em>file</em> can be an on-disk file
  534. opened for binary reading, an <a class="reference internal" href="io.html#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BytesIO</span></code></a> object, or any other
  535. custom object that meets this interface.</p>
  536. <p>The optional arguments <em>fix_imports</em>, <em>encoding</em> and <em>errors</em> are used
  537. to control compatibility support for pickle stream generated by Python 2.
  538. If <em>fix_imports</em> is true, pickle will try to map the old Python 2 names
  539. to the new names used in Python 3. The <em>encoding</em> and <em>errors</em> tell
  540. pickle how to decode 8-bit string instances pickled by Python 2;
  541. these default to ‘ASCII’ and ‘strict’, respectively. The <em>encoding</em> can
  542. be ‘bytes’ to read these 8-bit string instances as bytes objects.
  543. Using <code class="docutils literal notranslate"><span class="pre">encoding='latin1'</span></code> is required for unpickling NumPy arrays and
  544. instances of <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>, <a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> and
  545. <a class="reference internal" href="datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> pickled by Python 2.</p>
  546. <p>If <em>buffers</em> is None (the default), then all data necessary for
  547. deserialization must be contained in the pickle stream. This means
  548. that the <em>buffer_callback</em> argument was None when a <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a>
  549. was instantiated (or when <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a> or <a class="reference internal" href="#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> was called).</p>
  550. <p>If <em>buffers</em> is not None, it should be an iterable of buffer-enabled
  551. objects that is consumed each time the pickle stream references
  552. an <a class="reference internal" href="#pickle-oob"><span class="std std-ref">out-of-band</span></a> buffer view. Such buffers have been
  553. given in order to the <em>buffer_callback</em> of a Pickler object.</p>
  554. <div class="versionchanged">
  555. <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>buffers</em> argument was added.</p>
  556. </div>
  557. <dl class="py method">
  558. <dt class="sig sig-object py" id="pickle.Unpickler.load">
  559. <span class="sig-name descname"><span class="pre">load</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler.load" title="Link to this definition">¶</a></dt>
  560. <dd><p>Read the pickled representation of an object from the open file object
  561. given in the constructor, and return the reconstituted object hierarchy
  562. specified therein. Bytes past the pickled representation of the object
  563. are ignored.</p>
  564. </dd></dl>
  565. <dl class="py method">
  566. <dt class="sig sig-object py" id="pickle.Unpickler.persistent_load">
  567. <span class="sig-name descname"><span class="pre">persistent_load</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">pid</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler.persistent_load" title="Link to this definition">¶</a></dt>
  568. <dd><p>Raise an <a class="reference internal" href="#pickle.UnpicklingError" title="pickle.UnpicklingError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnpicklingError</span></code></a> by default.</p>
  569. <p>If defined, <a class="reference internal" href="#pickle.Unpickler.persistent_load" title="pickle.Unpickler.persistent_load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_load()</span></code></a> should return the object specified by
  570. the persistent ID <em>pid</em>. If an invalid persistent ID is encountered, an
  571. <a class="reference internal" href="#pickle.UnpicklingError" title="pickle.UnpicklingError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnpicklingError</span></code></a> should be raised.</p>
  572. <p>See <a class="reference internal" href="#pickle-persistent"><span class="std std-ref">Persistence of External Objects</span></a> for details and examples of uses.</p>
  573. </dd></dl>
  574. <dl class="py method">
  575. <dt class="sig sig-object py" id="pickle.Unpickler.find_class">
  576. <span class="sig-name descname"><span class="pre">find_class</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">module</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler.find_class" title="Link to this definition">¶</a></dt>
  577. <dd><p>Import <em>module</em> if necessary and return the object called <em>name</em> from it,
  578. where the <em>module</em> and <em>name</em> arguments are <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> objects. Note,
  579. unlike its name suggests, <a class="reference internal" href="#pickle.Unpickler.find_class" title="pickle.Unpickler.find_class"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find_class()</span></code></a> is also used for finding
  580. functions.</p>
  581. <p>Subclasses may override this to gain control over what type of objects and
  582. how they can be loaded, potentially reducing security risks. Refer to
  583. <a class="reference internal" href="#pickle-restrict"><span class="std std-ref">Restricting Globals</span></a> for details.</p>
  584. <p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">pickle.find_class</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">module</span></code>, <code class="docutils literal notranslate"><span class="pre">name</span></code>.</p>
  585. </dd></dl>
  586. </dd></dl>
  587. <dl class="py class">
  588. <dt class="sig sig-object py" id="pickle.PickleBuffer">
  589. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">pickle.</span></span><span class="sig-name descname"><span class="pre">PickleBuffer</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.PickleBuffer" title="Link to this definition">¶</a></dt>
  590. <dd><p>A wrapper for a buffer representing picklable data. <em>buffer</em> must be a
  591. <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">buffer-providing</span></a> object, such as a
  592. <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> or a N-dimensional array.</p>
  593. <p><a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a> is itself a buffer provider, therefore it is
  594. possible to pass it to other APIs expecting a buffer-providing object,
  595. such as <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.</p>
  596. <p><a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a> objects can only be serialized using pickle
  597. protocol 5 or higher. They are eligible for
  598. <a class="reference internal" href="#pickle-oob"><span class="std std-ref">out-of-band serialization</span></a>.</p>
  599. <div class="versionadded">
  600. <p><span class="versionmodified added">New in version 3.8.</span></p>
  601. </div>
  602. <dl class="py method">
  603. <dt class="sig sig-object py" id="pickle.PickleBuffer.raw">
  604. <span class="sig-name descname"><span class="pre">raw</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.PickleBuffer.raw" title="Link to this definition">¶</a></dt>
  605. <dd><p>Return a <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> of the memory area underlying this buffer.
  606. The returned object is a one-dimensional, C-contiguous memoryview
  607. with format <code class="docutils literal notranslate"><span class="pre">B</span></code> (unsigned bytes). <a class="reference internal" href="exceptions.html#BufferError" title="BufferError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BufferError</span></code></a> is raised if
  608. the buffer is neither C- nor Fortran-contiguous.</p>
  609. </dd></dl>
  610. <dl class="py method">
  611. <dt class="sig sig-object py" id="pickle.PickleBuffer.release">
  612. <span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.PickleBuffer.release" title="Link to this definition">¶</a></dt>
  613. <dd><p>Release the underlying buffer exposed by the PickleBuffer object.</p>
  614. </dd></dl>
  615. </dd></dl>
  616. </section>
  617. <section id="what-can-be-pickled-and-unpickled">
  618. <span id="pickle-picklable"></span><h2>What can be pickled and unpickled?<a class="headerlink" href="#what-can-be-pickled-and-unpickled" title="Link to this heading">¶</a></h2>
  619. <p>The following types can be pickled:</p>
  620. <ul class="simple">
  621. <li><p>built-in constants (<code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">False</span></code>, <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>, and
  622. <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>);</p></li>
  623. <li><p>integers, floating-point numbers, complex numbers;</p></li>
  624. <li><p>strings, bytes, bytearrays;</p></li>
  625. <li><p>tuples, lists, sets, and dictionaries containing only picklable objects;</p></li>
  626. <li><p>functions (built-in and user-defined) accessible from the top level of a
  627. module (using <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>, not <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a>);</p></li>
  628. <li><p>classes accessible from the top level of a module;</p></li>
  629. <li><p>instances of such classes whose the result of calling <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a>
  630. is picklable (see section <a class="reference internal" href="#pickle-inst"><span class="std std-ref">Pickling Class Instances</span></a> for details).</p></li>
  631. </ul>
  632. <p>Attempts to pickle unpicklable objects will raise the <a class="reference internal" href="#pickle.PicklingError" title="pickle.PicklingError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PicklingError</span></code></a>
  633. exception; when this happens, an unspecified number of bytes may have already
  634. been written to the underlying file. Trying to pickle a highly recursive data
  635. structure may exceed the maximum recursion depth, a <a class="reference internal" href="exceptions.html#RecursionError" title="RecursionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RecursionError</span></code></a> will be
  636. raised in this case. You can carefully raise this limit with
  637. <a class="reference internal" href="sys.html#sys.setrecursionlimit" title="sys.setrecursionlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setrecursionlimit()</span></code></a>.</p>
  638. <p>Note that functions (built-in and user-defined) are pickled by fully
  639. <a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a>, not by value. <a class="footnote-reference brackets" href="#id8" id="id3" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a> This means that only the function name is
  640. pickled, along with the name of the containing module and classes. Neither
  641. the function’s code, nor any of its function attributes are pickled. Thus the
  642. defining module must be importable in the unpickling environment, and the module
  643. must contain the named object, otherwise an exception will be raised. <a class="footnote-reference brackets" href="#id9" id="id4" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a></p>
  644. <p>Similarly, classes are pickled by fully qualified name, so the same restrictions in
  645. the unpickling environment apply. Note that none of the class’s code or data is
  646. pickled, so in the following example the class attribute <code class="docutils literal notranslate"><span class="pre">attr</span></code> is not
  647. restored in the unpickling environment:</p>
  648. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
  649. <span class="n">attr</span> <span class="o">=</span> <span class="s1">&#39;A class attribute&#39;</span>
  650. <span class="n">picklestring</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">Foo</span><span class="p">)</span>
  651. </pre></div>
  652. </div>
  653. <p>These restrictions are why picklable functions and classes must be defined at
  654. the top level of a module.</p>
  655. <p>Similarly, when class instances are pickled, their class’s code and data are not
  656. pickled along with them. Only the instance data are pickled. This is done on
  657. purpose, so you can fix bugs in a class or add methods to the class and still
  658. load objects that were created with an earlier version of the class. If you
  659. plan to have long-lived objects that will see many versions of a class, it may
  660. be worthwhile to put a version number in the objects so that suitable
  661. conversions can be made by the class’s <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method.</p>
  662. </section>
  663. <section id="pickling-class-instances">
  664. <span id="pickle-inst"></span><h2>Pickling Class Instances<a class="headerlink" href="#pickling-class-instances" title="Link to this heading">¶</a></h2>
  665. <p>In this section, we describe the general mechanisms available to you to define,
  666. customize, and control how class instances are pickled and unpickled.</p>
  667. <p>In most cases, no additional code is needed to make instances picklable. By
  668. default, pickle will retrieve the class and the attributes of an instance via
  669. introspection. When a class instance is unpickled, its <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method
  670. is usually <em>not</em> invoked. The default behaviour first creates an uninitialized
  671. instance and then restores the saved attributes. The following code shows an
  672. implementation of this behaviour:</p>
  673. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
  674. <span class="k">return</span> <span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="vm">__class__</span><span class="p">,</span> <span class="n">obj</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">)</span>
  675. <span class="k">def</span> <span class="nf">restore</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">attributes</span><span class="p">):</span>
  676. <span class="n">obj</span> <span class="o">=</span> <span class="bp">cls</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>
  677. <span class="n">obj</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">attributes</span><span class="p">)</span>
  678. <span class="k">return</span> <span class="n">obj</span>
  679. </pre></div>
  680. </div>
  681. <p>Classes can alter the default behaviour by providing one or several special
  682. methods:</p>
  683. <dl class="py method">
  684. <dt class="sig sig-object py" id="object.__getnewargs_ex__">
  685. <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__getnewargs_ex__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__getnewargs_ex__" title="Link to this definition">¶</a></dt>
  686. <dd><p>In protocols 2 and newer, classes that implements the
  687. <a class="reference internal" href="#object.__getnewargs_ex__" title="object.__getnewargs_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs_ex__()</span></code></a> method can dictate the values passed to the
  688. <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method upon unpickling. The method must return a pair
  689. <code class="docutils literal notranslate"><span class="pre">(args,</span> <span class="pre">kwargs)</span></code> where <em>args</em> is a tuple of positional arguments
  690. and <em>kwargs</em> a dictionary of named arguments for constructing the
  691. object. Those will be passed to the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method upon
  692. unpickling.</p>
  693. <p>You should implement this method if the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method of your
  694. class requires keyword-only arguments. Otherwise, it is recommended for
  695. compatibility to implement <a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a>.</p>
  696. <div class="versionchanged">
  697. <p><span class="versionmodified changed">Changed in version 3.6: </span><a class="reference internal" href="#object.__getnewargs_ex__" title="object.__getnewargs_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs_ex__()</span></code></a> is now used in protocols 2 and 3.</p>
  698. </div>
  699. </dd></dl>
  700. <dl class="py method">
  701. <dt class="sig sig-object py" id="object.__getnewargs__">
  702. <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__getnewargs__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__getnewargs__" title="Link to this definition">¶</a></dt>
  703. <dd><p>This method serves a similar purpose as <a class="reference internal" href="#object.__getnewargs_ex__" title="object.__getnewargs_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs_ex__()</span></code></a>, but
  704. supports only positional arguments. It must return a tuple of arguments
  705. <code class="docutils literal notranslate"><span class="pre">args</span></code> which will be passed to the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method upon unpickling.</p>
  706. <p><a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a> will not be called if <a class="reference internal" href="#object.__getnewargs_ex__" title="object.__getnewargs_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs_ex__()</span></code></a> is
  707. defined.</p>
  708. <div class="versionchanged">
  709. <p><span class="versionmodified changed">Changed in version 3.6: </span>Before Python 3.6, <a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a> was called instead of
  710. <a class="reference internal" href="#object.__getnewargs_ex__" title="object.__getnewargs_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs_ex__()</span></code></a> in protocols 2 and 3.</p>
  711. </div>
  712. </dd></dl>
  713. <dl class="py method">
  714. <dt class="sig sig-object py" id="object.__getstate__">
  715. <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__getstate__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__getstate__" title="Link to this definition">¶</a></dt>
  716. <dd><p>Classes can further influence how their instances are pickled by overriding
  717. the method <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a>. It is called and the returned object
  718. is pickled as the contents for the instance, instead of a default state.
  719. There are several cases:</p>
  720. <ul class="simple">
  721. <li><p>For a class that has no instance <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and no
  722. <a class="reference internal" href="../reference/datamodel.html#object.__slots__" title="object.__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a>, the default state is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
  723. <li><p>For a class that has an instance <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and no
  724. <a class="reference internal" href="../reference/datamodel.html#object.__slots__" title="object.__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a>, the default state is <code class="docutils literal notranslate"><span class="pre">self.__dict__</span></code>.</p></li>
  725. <li><p>For a class that has an instance <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and
  726. <a class="reference internal" href="../reference/datamodel.html#object.__slots__" title="object.__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a>, the default state is a tuple consisting of two
  727. dictionaries: <code class="docutils literal notranslate"><span class="pre">self.__dict__</span></code>, and a dictionary mapping slot
  728. names to slot values. Only slots that have a value are
  729. included in the latter.</p></li>
  730. <li><p>For a class that has <a class="reference internal" href="../reference/datamodel.html#object.__slots__" title="object.__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a> and no instance
  731. <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>, the default state is a tuple whose first item
  732. is <code class="docutils literal notranslate"><span class="pre">None</span></code> and whose second item is a dictionary mapping slot names
  733. to slot values described in the previous bullet.</p></li>
  734. </ul>
  735. <div class="versionchanged">
  736. <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the default implementation of the <code class="docutils literal notranslate"><span class="pre">__getstate__()</span></code> method in the
  737. <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class.</p>
  738. </div>
  739. </dd></dl>
  740. <dl class="py method">
  741. <dt class="sig sig-object py" id="object.__setstate__">
  742. <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__setstate__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">state</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setstate__" title="Link to this definition">¶</a></dt>
  743. <dd><p>Upon unpickling, if the class defines <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>, it is called with
  744. the unpickled state. In that case, there is no requirement for the state
  745. object to be a dictionary. Otherwise, the pickled state must be a dictionary
  746. and its items are assigned to the new instance’s dictionary.</p>
  747. <div class="admonition note">
  748. <p class="admonition-title">Note</p>
  749. <p>If <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> returns a state with value <code class="docutils literal notranslate"><span class="pre">None</span></code> at pickling,
  750. the <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method will not be called upon unpickling.</p>
  751. </div>
  752. </dd></dl>
  753. <p>Refer to the section <a class="reference internal" href="#pickle-state"><span class="std std-ref">Handling Stateful Objects</span></a> for more information about how to use
  754. the methods <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> and <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>.</p>
  755. <div class="admonition note">
  756. <p class="admonition-title">Note</p>
  757. <p>At unpickling time, some methods like <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>,
  758. <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>, or <a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> may be called upon the
  759. instance. In case those methods rely on some internal invariant being
  760. true, the type should implement <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> to establish such an
  761. invariant, as <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> is not called when unpickling an
  762. instance.</p>
  763. </div>
  764. <p id="index-5">As we shall see, pickle does not use directly the methods described above. In
  765. fact, these methods are part of the copy protocol which implements the
  766. <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> special method. The copy protocol provides a unified
  767. interface for retrieving the data necessary for pickling and copying
  768. objects. <a class="footnote-reference brackets" href="#id10" id="id5" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a></p>
  769. <p>Although powerful, implementing <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> directly in your classes is
  770. error prone. For this reason, class designers should use the high-level
  771. interface (i.e., <a class="reference internal" href="#object.__getnewargs_ex__" title="object.__getnewargs_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs_ex__()</span></code></a>, <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> and
  772. <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>) whenever possible. We will show, however, cases where
  773. using <code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code> is the only option or leads to more efficient pickling
  774. or both.</p>
  775. <dl class="py method">
  776. <dt class="sig sig-object py" id="object.__reduce__">
  777. <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__reduce__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__reduce__" title="Link to this definition">¶</a></dt>
  778. <dd><p>The interface is currently defined as follows. The <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method
  779. takes no argument and shall return either a string or preferably a tuple (the
  780. returned object is often referred to as the “reduce value”).</p>
  781. <p>If a string is returned, the string should be interpreted as the name of a
  782. global variable. It should be the object’s local name relative to its
  783. module; the pickle module searches the module namespace to determine the
  784. object’s module. This behaviour is typically useful for singletons.</p>
  785. <p>When a tuple is returned, it must be between two and six items long.
  786. Optional items can either be omitted, or <code class="docutils literal notranslate"><span class="pre">None</span></code> can be provided as their
  787. value. The semantics of each item are in order:</p>
  788. <ul>
  789. <li><p>A callable object that will be called to create the initial version of the
  790. object.</p></li>
  791. <li><p>A tuple of arguments for the callable object. An empty tuple must be given
  792. if the callable does not accept any argument.</p></li>
  793. <li><p>Optionally, the object’s state, which will be passed to the object’s
  794. <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method as previously described. If the object has no
  795. such method then, the value must be a dictionary and it will be added to
  796. the object’s <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute.</p></li>
  797. <li><p>Optionally, an iterator (and not a sequence) yielding successive items.
  798. These items will be appended to the object either using
  799. <code class="docutils literal notranslate"><span class="pre">obj.append(item)</span></code> or, in batch, using <code class="docutils literal notranslate"><span class="pre">obj.extend(list_of_items)</span></code>.
  800. This is primarily used for list subclasses, but may be used by other
  801. classes as long as they have
  802. <a class="reference internal" href="stdtypes.html#typesseq-common"><span class="std std-ref">append and extend methods</span></a> with
  803. the appropriate signature. (Whether <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code> is
  804. used depends on which pickle protocol version is used as well as the number
  805. of items to append, so both must be supported.)</p></li>
  806. <li><p>Optionally, an iterator (not a sequence) yielding successive key-value
  807. pairs. These items will be stored to the object using <code class="docutils literal notranslate"><span class="pre">obj[key]</span> <span class="pre">=</span>
  808. <span class="pre">value</span></code>. This is primarily used for dictionary subclasses, but may be used
  809. by other classes as long as they implement <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>.</p></li>
  810. <li><p>Optionally, a callable with a <code class="docutils literal notranslate"><span class="pre">(obj,</span> <span class="pre">state)</span></code> signature. This
  811. callable allows the user to programmatically control the state-updating
  812. behavior of a specific object, instead of using <code class="docutils literal notranslate"><span class="pre">obj</span></code>’s static
  813. <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method. If not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this callable will have
  814. priority over <code class="docutils literal notranslate"><span class="pre">obj</span></code>’s <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>.</p>
  815. <div class="versionadded">
  816. <p><span class="versionmodified added">New in version 3.8: </span>The optional sixth tuple item, <code class="docutils literal notranslate"><span class="pre">(obj,</span> <span class="pre">state)</span></code>, was added.</p>
  817. </div>
  818. </li>
  819. </ul>
  820. </dd></dl>
  821. <dl class="py method">
  822. <dt class="sig sig-object py" id="object.__reduce_ex__">
  823. <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__reduce_ex__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reduce_ex__" title="Link to this definition">¶</a></dt>
  824. <dd><p>Alternatively, a <a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a> method may be defined. The only
  825. difference is this method should take a single integer argument, the protocol
  826. version. When defined, pickle will prefer it over the <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>
  827. method. In addition, <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> automatically becomes a synonym for
  828. the extended version. The main use for this method is to provide
  829. backwards-compatible reduce values for older Python releases.</p>
  830. </dd></dl>
  831. <section id="persistence-of-external-objects">
  832. <span id="pickle-persistent"></span><h3>Persistence of External Objects<a class="headerlink" href="#persistence-of-external-objects" title="Link to this heading">¶</a></h3>
  833. <p id="index-6">For the benefit of object persistence, the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module supports the
  834. notion of a reference to an object outside the pickled data stream. Such
  835. objects are referenced by a persistent ID, which should be either a string of
  836. alphanumeric characters (for protocol 0) <a class="footnote-reference brackets" href="#id11" id="id6" role="doc-noteref"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></a> or just an arbitrary object (for
  837. any newer protocol).</p>
  838. <p>The resolution of such persistent IDs is not defined by the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>
  839. module; it will delegate this resolution to the user-defined methods on the
  840. pickler and unpickler, <a class="reference internal" href="#pickle.Pickler.persistent_id" title="pickle.Pickler.persistent_id"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_id()</span></code></a> and
  841. <a class="reference internal" href="#pickle.Unpickler.persistent_load" title="pickle.Unpickler.persistent_load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_load()</span></code></a> respectively.</p>
  842. <p>To pickle objects that have an external persistent ID, the pickler must have a
  843. custom <a class="reference internal" href="#pickle.Pickler.persistent_id" title="pickle.Pickler.persistent_id"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_id()</span></code></a> method that takes an object as an
  844. argument and returns either <code class="docutils literal notranslate"><span class="pre">None</span></code> or the persistent ID for that object.
  845. When <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned, the pickler simply pickles the object as normal.
  846. When a persistent ID string is returned, the pickler will pickle that object,
  847. along with a marker so that the unpickler will recognize it as a persistent ID.</p>
  848. <p>To unpickle external objects, the unpickler must have a custom
  849. <a class="reference internal" href="#pickle.Unpickler.persistent_load" title="pickle.Unpickler.persistent_load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_load()</span></code></a> method that takes a persistent ID object and
  850. returns the referenced object.</p>
  851. <p>Here is a comprehensive example presenting how persistent ID can be used to
  852. pickle external objects by reference.</p>
  853. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Simple example presenting how persistent ID can be used to pickle</span>
  854. <span class="c1"># external objects by reference.</span>
  855. <span class="kn">import</span> <span class="nn">pickle</span>
  856. <span class="kn">import</span> <span class="nn">sqlite3</span>
  857. <span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">namedtuple</span>
  858. <span class="c1"># Simple class representing a record in our database.</span>
  859. <span class="n">MemoRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s2">&quot;MemoRecord&quot;</span><span class="p">,</span> <span class="s2">&quot;key, task&quot;</span><span class="p">)</span>
  860. <span class="k">class</span> <span class="nc">DBPickler</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">Pickler</span><span class="p">):</span>
  861. <span class="k">def</span> <span class="nf">persistent_id</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
  862. <span class="c1"># Instead of pickling MemoRecord as a regular class instance, we emit a</span>
  863. <span class="c1"># persistent ID.</span>
  864. <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">MemoRecord</span><span class="p">):</span>
  865. <span class="c1"># Here, our persistent ID is simply a tuple, containing a tag and a</span>
  866. <span class="c1"># key, which refers to a specific record in the database.</span>
  867. <span class="k">return</span> <span class="p">(</span><span class="s2">&quot;MemoRecord&quot;</span><span class="p">,</span> <span class="n">obj</span><span class="o">.</span><span class="n">key</span><span class="p">)</span>
  868. <span class="k">else</span><span class="p">:</span>
  869. <span class="c1"># If obj does not have a persistent ID, return None. This means obj</span>
  870. <span class="c1"># needs to be pickled as usual.</span>
  871. <span class="k">return</span> <span class="kc">None</span>
  872. <span class="k">class</span> <span class="nc">DBUnpickler</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">Unpickler</span><span class="p">):</span>
  873. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">file</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
  874. <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
  875. <span class="bp">self</span><span class="o">.</span><span class="n">connection</span> <span class="o">=</span> <span class="n">connection</span>
  876. <span class="k">def</span> <span class="nf">persistent_load</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">pid</span><span class="p">):</span>
  877. <span class="c1"># This method is invoked whenever a persistent ID is encountered.</span>
  878. <span class="c1"># Here, pid is the tuple returned by DBPickler.</span>
  879. <span class="n">cursor</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
  880. <span class="n">type_tag</span><span class="p">,</span> <span class="n">key_id</span> <span class="o">=</span> <span class="n">pid</span>
  881. <span class="k">if</span> <span class="n">type_tag</span> <span class="o">==</span> <span class="s2">&quot;MemoRecord&quot;</span><span class="p">:</span>
  882. <span class="c1"># Fetch the referenced record from the database and return it.</span>
  883. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;SELECT * FROM memos WHERE key=?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">key_id</span><span class="p">),))</span>
  884. <span class="n">key</span><span class="p">,</span> <span class="n">task</span> <span class="o">=</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
  885. <span class="k">return</span> <span class="n">MemoRecord</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">task</span><span class="p">)</span>
  886. <span class="k">else</span><span class="p">:</span>
  887. <span class="c1"># Always raises an error if you cannot return the correct object.</span>
  888. <span class="c1"># Otherwise, the unpickler will think None is the object referenced</span>
  889. <span class="c1"># by the persistent ID.</span>
  890. <span class="k">raise</span> <span class="n">pickle</span><span class="o">.</span><span class="n">UnpicklingError</span><span class="p">(</span><span class="s2">&quot;unsupported persistent object&quot;</span><span class="p">)</span>
  891. <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  892. <span class="kn">import</span> <span class="nn">io</span>
  893. <span class="kn">import</span> <span class="nn">pprint</span>
  894. <span class="c1"># Initialize and populate our database.</span>
  895. <span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
  896. <span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
  897. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)&quot;</span><span class="p">)</span>
  898. <span class="n">tasks</span> <span class="o">=</span> <span class="p">(</span>
  899. <span class="s1">&#39;give food to fish&#39;</span><span class="p">,</span>
  900. <span class="s1">&#39;prepare group meeting&#39;</span><span class="p">,</span>
  901. <span class="s1">&#39;fight with a zebra&#39;</span><span class="p">,</span>
  902. <span class="p">)</span>
  903. <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">tasks</span><span class="p">:</span>
  904. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;INSERT INTO memos VALUES(NULL, ?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">task</span><span class="p">,))</span>
  905. <span class="c1"># Fetch the records to be pickled.</span>
  906. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;SELECT * FROM memos&quot;</span><span class="p">)</span>
  907. <span class="n">memos</span> <span class="o">=</span> <span class="p">[</span><span class="n">MemoRecord</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">task</span><span class="p">)</span> <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">cursor</span><span class="p">]</span>
  908. <span class="c1"># Save the records using our custom DBPickler.</span>
  909. <span class="n">file</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">()</span>
  910. <span class="n">DBPickler</span><span class="p">(</span><span class="n">file</span><span class="p">)</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">memos</span><span class="p">)</span>
  911. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Pickled records:&quot;</span><span class="p">)</span>
  912. <span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">memos</span><span class="p">)</span>
  913. <span class="c1"># Update a record, just for good measure.</span>
  914. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;UPDATE memos SET task=&#39;learn italian&#39; WHERE key=1&quot;</span><span class="p">)</span>
  915. <span class="c1"># Load the records from the pickle data stream.</span>
  916. <span class="n">file</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  917. <span class="n">memos</span> <span class="o">=</span> <span class="n">DBUnpickler</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">conn</span><span class="p">)</span><span class="o">.</span><span class="n">load</span><span class="p">()</span>
  918. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unpickled records:&quot;</span><span class="p">)</span>
  919. <span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">memos</span><span class="p">)</span>
  920. <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
  921. <span class="n">main</span><span class="p">()</span>
  922. </pre></div>
  923. </div>
  924. </section>
  925. <section id="dispatch-tables">
  926. <span id="pickle-dispatch"></span><h3>Dispatch Tables<a class="headerlink" href="#dispatch-tables" title="Link to this heading">¶</a></h3>
  927. <p>If one wants to customize pickling of some classes without disturbing
  928. any other code which depends on pickling, then one can create a
  929. pickler with a private dispatch table.</p>
  930. <p>The global dispatch table managed by the <a class="reference internal" href="copyreg.html#module-copyreg" title="copyreg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code></a> module is
  931. available as <code class="xref py py-data docutils literal notranslate"><span class="pre">copyreg.dispatch_table</span></code>. Therefore, one may
  932. choose to use a modified copy of <code class="xref py py-data docutils literal notranslate"><span class="pre">copyreg.dispatch_table</span></code> as a
  933. private dispatch table.</p>
  934. <p>For example</p>
  935. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">()</span>
  936. <span class="n">p</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">Pickler</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  937. <span class="n">p</span><span class="o">.</span><span class="n">dispatch_table</span> <span class="o">=</span> <span class="n">copyreg</span><span class="o">.</span><span class="n">dispatch_table</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
  938. <span class="n">p</span><span class="o">.</span><span class="n">dispatch_table</span><span class="p">[</span><span class="n">SomeClass</span><span class="p">]</span> <span class="o">=</span> <span class="n">reduce_SomeClass</span>
  939. </pre></div>
  940. </div>
  941. <p>creates an instance of <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">pickle.Pickler</span></code></a> with a private dispatch
  942. table which handles the <code class="docutils literal notranslate"><span class="pre">SomeClass</span></code> class specially. Alternatively,
  943. the code</p>
  944. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyPickler</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">Pickler</span><span class="p">):</span>
  945. <span class="n">dispatch_table</span> <span class="o">=</span> <span class="n">copyreg</span><span class="o">.</span><span class="n">dispatch_table</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
  946. <span class="n">dispatch_table</span><span class="p">[</span><span class="n">SomeClass</span><span class="p">]</span> <span class="o">=</span> <span class="n">reduce_SomeClass</span>
  947. <span class="n">f</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">()</span>
  948. <span class="n">p</span> <span class="o">=</span> <span class="n">MyPickler</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  949. </pre></div>
  950. </div>
  951. <p>does the same but all instances of <code class="docutils literal notranslate"><span class="pre">MyPickler</span></code> will by default
  952. share the private dispatch table. On the other hand, the code</p>
  953. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">copyreg</span><span class="o">.</span><span class="n">pickle</span><span class="p">(</span><span class="n">SomeClass</span><span class="p">,</span> <span class="n">reduce_SomeClass</span><span class="p">)</span>
  954. <span class="n">f</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">()</span>
  955. <span class="n">p</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">Pickler</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  956. </pre></div>
  957. </div>
  958. <p>modifies the global dispatch table shared by all users of the <a class="reference internal" href="copyreg.html#module-copyreg" title="copyreg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code></a> module.</p>
  959. </section>
  960. <section id="handling-stateful-objects">
  961. <span id="pickle-state"></span><h3>Handling Stateful Objects<a class="headerlink" href="#handling-stateful-objects" title="Link to this heading">¶</a></h3>
  962. <p id="index-7">Here’s an example that shows how to modify pickling behavior for a class.
  963. The <code class="xref py py-class docutils literal notranslate"><span class="pre">TextReader</span></code> class below opens a text file, and returns the line number and
  964. line contents each time its <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code> method is called. If a
  965. <code class="xref py py-class docutils literal notranslate"><span class="pre">TextReader</span></code> instance is pickled, all attributes <em>except</em> the file object
  966. member are saved. When the instance is unpickled, the file is reopened, and
  967. reading resumes from the last location. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code> and
  968. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code> methods are used to implement this behavior.</p>
  969. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">TextReader</span><span class="p">:</span>
  970. <span class="w"> </span><span class="sd">&quot;&quot;&quot;Print and number lines in a text file.&quot;&quot;&quot;</span>
  971. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">filename</span><span class="p">):</span>
  972. <span class="bp">self</span><span class="o">.</span><span class="n">filename</span> <span class="o">=</span> <span class="n">filename</span>
  973. <span class="bp">self</span><span class="o">.</span><span class="n">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
  974. <span class="bp">self</span><span class="o">.</span><span class="n">lineno</span> <span class="o">=</span> <span class="mi">0</span>
  975. <span class="k">def</span> <span class="nf">readline</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  976. <span class="bp">self</span><span class="o">.</span><span class="n">lineno</span> <span class="o">+=</span> <span class="mi">1</span>
  977. <span class="n">line</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">file</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  978. <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
  979. <span class="k">return</span> <span class="kc">None</span>
  980. <span class="k">if</span> <span class="n">line</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">):</span>
  981. <span class="n">line</span> <span class="o">=</span> <span class="n">line</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
  982. <span class="k">return</span> <span class="s2">&quot;</span><span class="si">%i</span><span class="s2">: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">lineno</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span>
  983. <span class="k">def</span> <span class="nf">__getstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  984. <span class="c1"># Copy the object&#39;s state from self.__dict__ which contains</span>
  985. <span class="c1"># all our instance attributes. Always use the dict.copy()</span>
  986. <span class="c1"># method to avoid modifying the original state.</span>
  987. <span class="n">state</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
  988. <span class="c1"># Remove the unpicklable entries.</span>
  989. <span class="k">del</span> <span class="n">state</span><span class="p">[</span><span class="s1">&#39;file&#39;</span><span class="p">]</span>
  990. <span class="k">return</span> <span class="n">state</span>
  991. <span class="k">def</span> <span class="nf">__setstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">state</span><span class="p">):</span>
  992. <span class="c1"># Restore instance attributes (i.e., filename and lineno).</span>
  993. <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>
  994. <span class="c1"># Restore the previously opened file&#39;s state. To do so, we need to</span>
  995. <span class="c1"># reopen it and read from it until the line count is restored.</span>
  996. <span class="n">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">filename</span><span class="p">)</span>
  997. <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">lineno</span><span class="p">):</span>
  998. <span class="n">file</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  999. <span class="c1"># Finally, save the file.</span>
  1000. <span class="bp">self</span><span class="o">.</span><span class="n">file</span> <span class="o">=</span> <span class="n">file</span>
  1001. </pre></div>
  1002. </div>
  1003. <p>A sample usage might be something like this:</p>
  1004. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">reader</span> <span class="o">=</span> <span class="n">TextReader</span><span class="p">(</span><span class="s2">&quot;hello.txt&quot;</span><span class="p">)</span>
  1005. <span class="gp">&gt;&gt;&gt; </span><span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  1006. <span class="go">&#39;1: Hello world!&#39;</span>
  1007. <span class="gp">&gt;&gt;&gt; </span><span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  1008. <span class="go">&#39;2: I am line number two.&#39;</span>
  1009. <span class="gp">&gt;&gt;&gt; </span><span class="n">new_reader</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">reader</span><span class="p">))</span>
  1010. <span class="gp">&gt;&gt;&gt; </span><span class="n">new_reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  1011. <span class="go">&#39;3: Goodbye!&#39;</span>
  1012. </pre></div>
  1013. </div>
  1014. </section>
  1015. </section>
  1016. <section id="custom-reduction-for-types-functions-and-other-objects">
  1017. <span id="reducer-override"></span><h2>Custom Reduction for Types, Functions, and Other Objects<a class="headerlink" href="#custom-reduction-for-types-functions-and-other-objects" title="Link to this heading">¶</a></h2>
  1018. <div class="versionadded">
  1019. <p><span class="versionmodified added">New in version 3.8.</span></p>
  1020. </div>
  1021. <p>Sometimes, <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a> may not be flexible enough.
  1022. In particular we may want to customize pickling based on another criterion
  1023. than the object’s type, or we may want to customize the pickling of
  1024. functions and classes.</p>
  1025. <p>For those cases, it is possible to subclass from the <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> class and
  1026. implement a <a class="reference internal" href="#pickle.Pickler.reducer_override" title="pickle.Pickler.reducer_override"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reducer_override()</span></code></a> method. This method can return an
  1027. arbitrary reduction tuple (see <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>). It can alternatively return
  1028. <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> to fallback to the traditional behavior.</p>
  1029. <p>If both the <a class="reference internal" href="#pickle.Pickler.dispatch_table" title="pickle.Pickler.dispatch_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dispatch_table</span></code></a> and
  1030. <a class="reference internal" href="#pickle.Pickler.reducer_override" title="pickle.Pickler.reducer_override"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reducer_override()</span></code></a> are defined, then
  1031. <a class="reference internal" href="#pickle.Pickler.reducer_override" title="pickle.Pickler.reducer_override"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reducer_override()</span></code></a> method takes priority.</p>
  1032. <div class="admonition note">
  1033. <p class="admonition-title">Note</p>
  1034. <p>For performance reasons, <a class="reference internal" href="#pickle.Pickler.reducer_override" title="pickle.Pickler.reducer_override"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reducer_override()</span></code></a> may not be
  1035. called for the following objects: <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">False</span></code>, and
  1036. exact instances of <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>,
  1037. <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>
  1038. and <a class="reference internal" href="stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
  1039. </div>
  1040. <p>Here is a simple example where we allow pickling and reconstructing
  1041. a given class:</p>
  1042. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">io</span>
  1043. <span class="kn">import</span> <span class="nn">pickle</span>
  1044. <span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
  1045. <span class="n">my_attribute</span> <span class="o">=</span> <span class="mi">1</span>
  1046. <span class="k">class</span> <span class="nc">MyPickler</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">Pickler</span><span class="p">):</span>
  1047. <span class="k">def</span> <span class="nf">reducer_override</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
  1048. <span class="w"> </span><span class="sd">&quot;&quot;&quot;Custom reducer for MyClass.&quot;&quot;&quot;</span>
  1049. <span class="k">if</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s2">&quot;__name__&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> <span class="o">==</span> <span class="s2">&quot;MyClass&quot;</span><span class="p">:</span>
  1050. <span class="k">return</span> <span class="nb">type</span><span class="p">,</span> <span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">obj</span><span class="o">.</span><span class="vm">__bases__</span><span class="p">,</span>
  1051. <span class="p">{</span><span class="s1">&#39;my_attribute&#39;</span><span class="p">:</span> <span class="n">obj</span><span class="o">.</span><span class="n">my_attribute</span><span class="p">})</span>
  1052. <span class="k">else</span><span class="p">:</span>
  1053. <span class="c1"># For any other object, fallback to usual reduction</span>
  1054. <span class="k">return</span> <span class="bp">NotImplemented</span>
  1055. <span class="n">f</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">()</span>
  1056. <span class="n">p</span> <span class="o">=</span> <span class="n">MyPickler</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  1057. <span class="n">p</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">MyClass</span><span class="p">)</span>
  1058. <span class="k">del</span> <span class="n">MyClass</span>
  1059. <span class="n">unpickled_class</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span>
  1060. <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">unpickled_class</span><span class="p">,</span> <span class="nb">type</span><span class="p">)</span>
  1061. <span class="k">assert</span> <span class="n">unpickled_class</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;MyClass&quot;</span>
  1062. <span class="k">assert</span> <span class="n">unpickled_class</span><span class="o">.</span><span class="n">my_attribute</span> <span class="o">==</span> <span class="mi">1</span>
  1063. </pre></div>
  1064. </div>
  1065. </section>
  1066. <section id="out-of-band-buffers">
  1067. <span id="pickle-oob"></span><h2>Out-of-band Buffers<a class="headerlink" href="#out-of-band-buffers" title="Link to this heading">¶</a></h2>
  1068. <div class="versionadded">
  1069. <p><span class="versionmodified added">New in version 3.8.</span></p>
  1070. </div>
  1071. <p>In some contexts, the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module is used to transfer massive amounts
  1072. of data. Therefore, it can be important to minimize the number of memory
  1073. copies, to preserve performance and resource consumption. However, normal
  1074. operation of the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module, as it transforms a graph-like structure
  1075. of objects into a sequential stream of bytes, intrinsically involves copying
  1076. data to and from the pickle stream.</p>
  1077. <p>This constraint can be eschewed if both the <em>provider</em> (the implementation
  1078. of the object types to be transferred) and the <em>consumer</em> (the implementation
  1079. of the communications system) support the out-of-band transfer facilities
  1080. provided by pickle protocol 5 and higher.</p>
  1081. <section id="provider-api">
  1082. <h3>Provider API<a class="headerlink" href="#provider-api" title="Link to this heading">¶</a></h3>
  1083. <p>The large data objects to be pickled must implement a <a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a>
  1084. method specialized for protocol 5 and higher, which returns a
  1085. <a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a> instance (instead of e.g. a <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> object)
  1086. for any large data.</p>
  1087. <p>A <a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a> object <em>signals</em> that the underlying buffer is
  1088. eligible for out-of-band data transfer. Those objects remain compatible
  1089. with normal usage of the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module. However, consumers can also
  1090. opt-in to tell <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> that they will handle those buffers by
  1091. themselves.</p>
  1092. </section>
  1093. <section id="consumer-api">
  1094. <h3>Consumer API<a class="headerlink" href="#consumer-api" title="Link to this heading">¶</a></h3>
  1095. <p>A communications system can enable custom handling of the <a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a>
  1096. objects generated when serializing an object graph.</p>
  1097. <p>On the sending side, it needs to pass a <em>buffer_callback</em> argument to
  1098. <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> (or to the <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a> or <a class="reference internal" href="#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> function), which
  1099. will be called with each <a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a> generated while pickling
  1100. the object graph. Buffers accumulated by the <em>buffer_callback</em> will not
  1101. see their data copied into the pickle stream, only a cheap marker will be
  1102. inserted.</p>
  1103. <p>On the receiving side, it needs to pass a <em>buffers</em> argument to
  1104. <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> (or to the <a class="reference internal" href="#pickle.load" title="pickle.load"><code class="xref py py-func docutils literal notranslate"><span class="pre">load()</span></code></a> or <a class="reference internal" href="#pickle.loads" title="pickle.loads"><code class="xref py py-func docutils literal notranslate"><span class="pre">loads()</span></code></a> function),
  1105. which is an iterable of the buffers which were passed to <em>buffer_callback</em>.
  1106. That iterable should produce buffers in the same order as they were passed
  1107. to <em>buffer_callback</em>. Those buffers will provide the data expected by the
  1108. reconstructors of the objects whose pickling produced the original
  1109. <a class="reference internal" href="#pickle.PickleBuffer" title="pickle.PickleBuffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleBuffer</span></code></a> objects.</p>
  1110. <p>Between the sending side and the receiving side, the communications system
  1111. is free to implement its own transfer mechanism for out-of-band buffers.
  1112. Potential optimizations include the use of shared memory or datatype-dependent
  1113. compression.</p>
  1114. </section>
  1115. <section id="example">
  1116. <h3>Example<a class="headerlink" href="#example" title="Link to this heading">¶</a></h3>
  1117. <p>Here is a trivial example where we implement a <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> subclass
  1118. able to participate in out-of-band buffer pickling:</p>
  1119. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ZeroCopyByteArray</span><span class="p">(</span><span class="nb">bytearray</span><span class="p">):</span>
  1120. <span class="k">def</span> <span class="nf">__reduce_ex__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">protocol</span><span class="p">):</span>
  1121. <span class="k">if</span> <span class="n">protocol</span> <span class="o">&gt;=</span> <span class="mi">5</span><span class="p">:</span>
  1122. <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_reconstruct</span><span class="p">,</span> <span class="p">(</span><span class="n">PickleBuffer</span><span class="p">(</span><span class="bp">self</span><span class="p">),),</span> <span class="kc">None</span>
  1123. <span class="k">else</span><span class="p">:</span>
  1124. <span class="c1"># PickleBuffer is forbidden with pickle protocols &lt;= 4.</span>
  1125. <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_reconstruct</span><span class="p">,</span> <span class="p">(</span><span class="nb">bytearray</span><span class="p">(</span><span class="bp">self</span><span class="p">),)</span>
  1126. <span class="nd">@classmethod</span>
  1127. <span class="k">def</span> <span class="nf">_reconstruct</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
  1128. <span class="k">with</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="k">as</span> <span class="n">m</span><span class="p">:</span>
  1129. <span class="c1"># Get a handle over the original buffer object</span>
  1130. <span class="n">obj</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">obj</span>
  1131. <span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="ow">is</span> <span class="bp">cls</span><span class="p">:</span>
  1132. <span class="c1"># Original buffer object is a ZeroCopyByteArray, return it</span>
  1133. <span class="c1"># as-is.</span>
  1134. <span class="k">return</span> <span class="n">obj</span>
  1135. <span class="k">else</span><span class="p">:</span>
  1136. <span class="k">return</span> <span class="bp">cls</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
  1137. </pre></div>
  1138. </div>
  1139. <p>The reconstructor (the <code class="docutils literal notranslate"><span class="pre">_reconstruct</span></code> class method) returns the buffer’s
  1140. providing object if it has the right type. This is an easy way to simulate
  1141. zero-copy behaviour on this toy example.</p>
  1142. <p>On the consumer side, we can pickle those objects the usual way, which
  1143. when unserialized will give us a copy of the original object:</p>
  1144. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">ZeroCopyByteArray</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span>
  1145. <span class="n">data</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">protocol</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
  1146. <span class="n">new_b</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
  1147. <span class="nb">print</span><span class="p">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">new_b</span><span class="p">)</span> <span class="c1"># True</span>
  1148. <span class="nb">print</span><span class="p">(</span><span class="n">b</span> <span class="ow">is</span> <span class="n">new_b</span><span class="p">)</span> <span class="c1"># False: a copy was made</span>
  1149. </pre></div>
  1150. </div>
  1151. <p>But if we pass a <em>buffer_callback</em> and then give back the accumulated
  1152. buffers when unserializing, we are able to get back the original object:</p>
  1153. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">ZeroCopyByteArray</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span>
  1154. <span class="n">buffers</span> <span class="o">=</span> <span class="p">[]</span>
  1155. <span class="n">data</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">protocol</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">buffer_callback</span><span class="o">=</span><span class="n">buffers</span><span class="o">.</span><span class="n">append</span><span class="p">)</span>
  1156. <span class="n">new_b</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">buffers</span><span class="o">=</span><span class="n">buffers</span><span class="p">)</span>
  1157. <span class="nb">print</span><span class="p">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">new_b</span><span class="p">)</span> <span class="c1"># True</span>
  1158. <span class="nb">print</span><span class="p">(</span><span class="n">b</span> <span class="ow">is</span> <span class="n">new_b</span><span class="p">)</span> <span class="c1"># True: no copy was made</span>
  1159. </pre></div>
  1160. </div>
  1161. <p>This example is limited by the fact that <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> allocates its
  1162. own memory: you cannot create a <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> instance that is backed
  1163. by another object’s memory. However, third-party datatypes such as NumPy
  1164. arrays do not have this limitation, and allow use of zero-copy pickling
  1165. (or making as few copies as possible) when transferring between distinct
  1166. processes or systems.</p>
  1167. <div class="admonition seealso">
  1168. <p class="admonition-title">See also</p>
  1169. <p><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0574/"><strong>PEP 574</strong></a> – Pickle protocol 5 with out-of-band data</p>
  1170. </div>
  1171. </section>
  1172. </section>
  1173. <section id="restricting-globals">
  1174. <span id="pickle-restrict"></span><h2>Restricting Globals<a class="headerlink" href="#restricting-globals" title="Link to this heading">¶</a></h2>
  1175. <p id="index-9">By default, unpickling will import any class or function that it finds in the
  1176. pickle data. For many applications, this behaviour is unacceptable as it
  1177. permits the unpickler to import and invoke arbitrary code. Just consider what
  1178. this hand-crafted pickle data stream does when loaded:</p>
  1179. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pickle</span>
  1180. <span class="gp">&gt;&gt;&gt; </span><span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;cos</span><span class="se">\n</span><span class="s2">system</span><span class="se">\n</span><span class="s2">(S&#39;echo hello world&#39;</span><span class="se">\n</span><span class="s2">tR.&quot;</span><span class="p">)</span>
  1181. <span class="go">hello world</span>
  1182. <span class="go">0</span>
  1183. </pre></div>
  1184. </div>
  1185. <p>In this example, the unpickler imports the <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a> function and then
  1186. apply the string argument “echo hello world”. Although this example is
  1187. inoffensive, it is not difficult to imagine one that could damage your system.</p>
  1188. <p>For this reason, you may want to control what gets unpickled by customizing
  1189. <a class="reference internal" href="#pickle.Unpickler.find_class" title="pickle.Unpickler.find_class"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Unpickler.find_class()</span></code></a>. Unlike its name suggests,
  1190. <a class="reference internal" href="#pickle.Unpickler.find_class" title="pickle.Unpickler.find_class"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Unpickler.find_class()</span></code></a> is called whenever a global (i.e., a class or
  1191. a function) is requested. Thus it is possible to either completely forbid
  1192. globals or restrict them to a safe subset.</p>
  1193. <p>Here is an example of an unpickler allowing only few safe classes from the
  1194. <a class="reference internal" href="builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a> module to be loaded:</p>
  1195. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">builtins</span>
  1196. <span class="kn">import</span> <span class="nn">io</span>
  1197. <span class="kn">import</span> <span class="nn">pickle</span>
  1198. <span class="n">safe_builtins</span> <span class="o">=</span> <span class="p">{</span>
  1199. <span class="s1">&#39;range&#39;</span><span class="p">,</span>
  1200. <span class="s1">&#39;complex&#39;</span><span class="p">,</span>
  1201. <span class="s1">&#39;set&#39;</span><span class="p">,</span>
  1202. <span class="s1">&#39;frozenset&#39;</span><span class="p">,</span>
  1203. <span class="s1">&#39;slice&#39;</span><span class="p">,</span>
  1204. <span class="p">}</span>
  1205. <span class="k">class</span> <span class="nc">RestrictedUnpickler</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">Unpickler</span><span class="p">):</span>
  1206. <span class="k">def</span> <span class="nf">find_class</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">module</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
  1207. <span class="c1"># Only allow safe classes from builtins.</span>
  1208. <span class="k">if</span> <span class="n">module</span> <span class="o">==</span> <span class="s2">&quot;builtins&quot;</span> <span class="ow">and</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">safe_builtins</span><span class="p">:</span>
  1209. <span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">builtins</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
  1210. <span class="c1"># Forbid everything else.</span>
  1211. <span class="k">raise</span> <span class="n">pickle</span><span class="o">.</span><span class="n">UnpicklingError</span><span class="p">(</span><span class="s2">&quot;global &#39;</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">&#39; is forbidden&quot;</span> <span class="o">%</span>
  1212. <span class="p">(</span><span class="n">module</span><span class="p">,</span> <span class="n">name</span><span class="p">))</span>
  1213. <span class="k">def</span> <span class="nf">restricted_loads</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
  1214. <span class="w"> </span><span class="sd">&quot;&quot;&quot;Helper function analogous to pickle.loads().&quot;&quot;&quot;</span>
  1215. <span class="k">return</span> <span class="n">RestrictedUnpickler</span><span class="p">(</span><span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">(</span><span class="n">s</span><span class="p">))</span><span class="o">.</span><span class="n">load</span><span class="p">()</span>
  1216. </pre></div>
  1217. </div>
  1218. <p>A sample usage of our unpickler working as intended:</p>
  1219. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">restricted_loads</span><span class="p">(</span><span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">15</span><span class="p">)]))</span>
  1220. <span class="go">[1, 2, range(0, 15)]</span>
  1221. <span class="gp">&gt;&gt;&gt; </span><span class="n">restricted_loads</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;cos</span><span class="se">\n</span><span class="s2">system</span><span class="se">\n</span><span class="s2">(S&#39;echo hello world&#39;</span><span class="se">\n</span><span class="s2">tR.&quot;</span><span class="p">)</span>
  1222. <span class="gt">Traceback (most recent call last):</span>
  1223. <span class="w"> </span><span class="c">...</span>
  1224. <span class="gr">pickle.UnpicklingError</span>: <span class="n">global &#39;os.system&#39; is forbidden</span>
  1225. <span class="gp">&gt;&gt;&gt; </span><span class="n">restricted_loads</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;cbuiltins</span><span class="se">\n</span><span class="s1">eval</span><span class="se">\n</span><span class="s1">&#39;</span>
  1226. <span class="gp">... </span> <span class="sa">b</span><span class="s1">&#39;(S</span><span class="se">\&#39;</span><span class="s1">getattr(__import__(&quot;os&quot;), &quot;system&quot;)&#39;</span>
  1227. <span class="gp">... </span> <span class="sa">b</span><span class="s1">&#39;(&quot;echo hello world&quot;)</span><span class="se">\&#39;\n</span><span class="s1">tR.&#39;</span><span class="p">)</span>
  1228. <span class="gt">Traceback (most recent call last):</span>
  1229. <span class="w"> </span><span class="c">...</span>
  1230. <span class="gr">pickle.UnpicklingError</span>: <span class="n">global &#39;builtins.eval&#39; is forbidden</span>
  1231. </pre></div>
  1232. </div>
  1233. <p>As our examples shows, you have to be careful with what you allow to be
  1234. unpickled. Therefore if security is a concern, you may want to consider
  1235. alternatives such as the marshalling API in <a class="reference internal" href="xmlrpc.client.html#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.client</span></code></a> or
  1236. third-party solutions.</p>
  1237. </section>
  1238. <section id="performance">
  1239. <h2>Performance<a class="headerlink" href="#performance" title="Link to this heading">¶</a></h2>
  1240. <p>Recent versions of the pickle protocol (from protocol 2 and upwards) feature
  1241. efficient binary encodings for several common features and built-in types.
  1242. Also, the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module has a transparent optimizer written in C.</p>
  1243. </section>
  1244. <section id="examples">
  1245. <span id="pickle-example"></span><h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2>
  1246. <p>For the simplest code, use the <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a> and <a class="reference internal" href="#pickle.load" title="pickle.load"><code class="xref py py-func docutils literal notranslate"><span class="pre">load()</span></code></a> functions.</p>
  1247. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pickle</span>
  1248. <span class="c1"># An arbitrary collection of objects supported by pickle.</span>
  1249. <span class="n">data</span> <span class="o">=</span> <span class="p">{</span>
  1250. <span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mi">3</span><span class="o">+</span><span class="mi">4</span><span class="n">j</span><span class="p">],</span>
  1251. <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="p">(</span><span class="s2">&quot;character string&quot;</span><span class="p">,</span> <span class="sa">b</span><span class="s2">&quot;byte string&quot;</span><span class="p">),</span>
  1252. <span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="p">{</span><span class="kc">None</span><span class="p">,</span> <span class="kc">True</span><span class="p">,</span> <span class="kc">False</span><span class="p">}</span>
  1253. <span class="p">}</span>
  1254. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;data.pickle&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  1255. <span class="c1"># Pickle the &#39;data&#39; dictionary using the highest protocol available.</span>
  1256. <span class="n">pickle</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">pickle</span><span class="o">.</span><span class="n">HIGHEST_PROTOCOL</span><span class="p">)</span>
  1257. </pre></div>
  1258. </div>
  1259. <p>The following example reads the resulting pickled data.</p>
  1260. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pickle</span>
  1261. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;data.pickle&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  1262. <span class="c1"># The protocol version used is detected automatically, so we do not</span>
  1263. <span class="c1"># have to specify it.</span>
  1264. <span class="n">data</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  1265. </pre></div>
  1266. </div>
  1267. <div class="admonition seealso">
  1268. <p class="admonition-title">See also</p>
  1269. <dl class="simple">
  1270. <dt>Module <a class="reference internal" href="copyreg.html#module-copyreg" title="copyreg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code></a></dt><dd><p>Pickle interface constructor registration for extension types.</p>
  1271. </dd>
  1272. <dt>Module <a class="reference internal" href="pickletools.html#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a></dt><dd><p>Tools for working with and analyzing pickled data.</p>
  1273. </dd>
  1274. <dt>Module <a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a></dt><dd><p>Indexed databases of objects; uses <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>.</p>
  1275. </dd>
  1276. <dt>Module <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a></dt><dd><p>Shallow and deep object copying.</p>
  1277. </dd>
  1278. <dt>Module <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a></dt><dd><p>High-performance serialization of built-in types.</p>
  1279. </dd>
  1280. </dl>
  1281. </div>
  1282. <p class="rubric">Footnotes</p>
  1283. <aside class="footnote-list brackets">
  1284. <aside class="footnote brackets" id="id7" role="doc-footnote">
  1285. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
  1286. <p>Don’t confuse this with the <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module</p>
  1287. </aside>
  1288. <aside class="footnote brackets" id="id8" role="doc-footnote">
  1289. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id3">2</a><span class="fn-bracket">]</span></span>
  1290. <p>This is why <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> functions cannot be pickled: all
  1291. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code> functions share the same name: <code class="docutils literal notranslate"><span class="pre">&lt;lambda&gt;</span></code>.</p>
  1292. </aside>
  1293. <aside class="footnote brackets" id="id9" role="doc-footnote">
  1294. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id4">3</a><span class="fn-bracket">]</span></span>
  1295. <p>The exception raised will likely be an <a class="reference internal" href="exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> or an
  1296. <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> but it could be something else.</p>
  1297. </aside>
  1298. <aside class="footnote brackets" id="id10" role="doc-footnote">
  1299. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id5">4</a><span class="fn-bracket">]</span></span>
  1300. <p>The <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a> module uses this protocol for shallow and deep copying
  1301. operations.</p>
  1302. </aside>
  1303. <aside class="footnote brackets" id="id11" role="doc-footnote">
  1304. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id6">5</a><span class="fn-bracket">]</span></span>
  1305. <p>The limitation on alphanumeric characters is due to the fact
  1306. that persistent IDs in protocol 0 are delimited by the newline
  1307. character. Therefore if any kind of newline characters occurs in
  1308. persistent IDs, the resulting pickled data will become unreadable.</p>
  1309. </aside>
  1310. </aside>
  1311. </section>
  1312. </section>
  1313. <div class="clearer"></div>
  1314. </div>
  1315. </div>
  1316. </div>
  1317. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1318. <div class="sphinxsidebarwrapper">
  1319. <div>
  1320. <h3><a href="../contents.html">Table of Contents</a></h3>
  1321. <ul>
  1322. <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a><ul>
  1323. <li><a class="reference internal" href="#relationship-to-other-python-modules">Relationship to other Python modules</a><ul>
  1324. <li><a class="reference internal" href="#comparison-with-marshal">Comparison with <code class="docutils literal notranslate"><span class="pre">marshal</span></code></a></li>
  1325. <li><a class="reference internal" href="#comparison-with-json">Comparison with <code class="docutils literal notranslate"><span class="pre">json</span></code></a></li>
  1326. </ul>
  1327. </li>
  1328. <li><a class="reference internal" href="#data-stream-format">Data stream format</a></li>
  1329. <li><a class="reference internal" href="#module-interface">Module Interface</a></li>
  1330. <li><a class="reference internal" href="#what-can-be-pickled-and-unpickled">What can be pickled and unpickled?</a></li>
  1331. <li><a class="reference internal" href="#pickling-class-instances">Pickling Class Instances</a><ul>
  1332. <li><a class="reference internal" href="#persistence-of-external-objects">Persistence of External Objects</a></li>
  1333. <li><a class="reference internal" href="#dispatch-tables">Dispatch Tables</a></li>
  1334. <li><a class="reference internal" href="#handling-stateful-objects">Handling Stateful Objects</a></li>
  1335. </ul>
  1336. </li>
  1337. <li><a class="reference internal" href="#custom-reduction-for-types-functions-and-other-objects">Custom Reduction for Types, Functions, and Other Objects</a></li>
  1338. <li><a class="reference internal" href="#out-of-band-buffers">Out-of-band Buffers</a><ul>
  1339. <li><a class="reference internal" href="#provider-api">Provider API</a></li>
  1340. <li><a class="reference internal" href="#consumer-api">Consumer API</a></li>
  1341. <li><a class="reference internal" href="#example">Example</a></li>
  1342. </ul>
  1343. </li>
  1344. <li><a class="reference internal" href="#restricting-globals">Restricting Globals</a></li>
  1345. <li><a class="reference internal" href="#performance">Performance</a></li>
  1346. <li><a class="reference internal" href="#examples">Examples</a></li>
  1347. </ul>
  1348. </li>
  1349. </ul>
  1350. </div>
  1351. <div>
  1352. <h4>Previous topic</h4>
  1353. <p class="topless"><a href="persistence.html"
  1354. title="previous chapter">Data Persistence</a></p>
  1355. </div>
  1356. <div>
  1357. <h4>Next topic</h4>
  1358. <p class="topless"><a href="copyreg.html"
  1359. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code> — Register <code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a></p>
  1360. </div>
  1361. <div role="note" aria-label="source link">
  1362. <h3>This Page</h3>
  1363. <ul class="this-page-menu">
  1364. <li><a href="../bugs.html">Report a Bug</a></li>
  1365. <li>
  1366. <a href="https://github.com/python/cpython/blob/main/Doc/library/pickle.rst"
  1367. rel="nofollow">Show Source
  1368. </a>
  1369. </li>
  1370. </ul>
  1371. </div>
  1372. </div>
  1373. <div id="sidebarbutton" title="Collapse sidebar">
  1374. <span>«</span>
  1375. </div>
  1376. </div>
  1377. <div class="clearer"></div>
  1378. </div>
  1379. <div class="related" role="navigation" aria-label="related navigation">
  1380. <h3>Navigation</h3>
  1381. <ul>
  1382. <li class="right" style="margin-right: 10px">
  1383. <a href="../genindex.html" title="General Index"
  1384. >index</a></li>
  1385. <li class="right" >
  1386. <a href="../py-modindex.html" title="Python Module Index"
  1387. >modules</a> |</li>
  1388. <li class="right" >
  1389. <a href="copyreg.html" title="copyreg — Register pickle support functions"
  1390. >next</a> |</li>
  1391. <li class="right" >
  1392. <a href="persistence.html" title="Data Persistence"
  1393. >previous</a> |</li>
  1394. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1395. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1396. <li class="switchers">
  1397. <div class="language_switcher_placeholder"></div>
  1398. <div class="version_switcher_placeholder"></div>
  1399. </li>
  1400. <li>
  1401. </li>
  1402. <li id="cpython-language-and-version">
  1403. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1404. </li>
  1405. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  1406. <li class="nav-item nav-item-2"><a href="persistence.html" >Data Persistence</a> &#187;</li>
  1407. <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a></li>
  1408. <li class="right">
  1409. <div class="inline-search" role="search">
  1410. <form class="inline-search" action="../search.html" method="get">
  1411. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1412. <input type="submit" value="Go" />
  1413. </form>
  1414. </div>
  1415. |
  1416. </li>
  1417. <li class="right">
  1418. <label class="theme-selector-label">
  1419. Theme
  1420. <select class="theme-selector" oninput="activateTheme(this.value)">
  1421. <option value="auto" selected>Auto</option>
  1422. <option value="light">Light</option>
  1423. <option value="dark">Dark</option>
  1424. </select>
  1425. </label> |</li>
  1426. </ul>
  1427. </div>
  1428. <div class="footer">
  1429. &copy;
  1430. <a href="../copyright.html">
  1431. Copyright
  1432. </a>
  1433. 2001-2024, Python Software Foundation.
  1434. <br />
  1435. This page is licensed under the Python Software Foundation License Version 2.
  1436. <br />
  1437. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1438. <br />
  1439. See <a href="/license.html">History and License</a> for more information.<br />
  1440. <br />
  1441. The Python Software Foundation is a non-profit corporation.
  1442. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1443. <br />
  1444. <br />
  1445. Last updated on Apr 09, 2024 (13:47 UTC).
  1446. <a href="/bugs.html">Found a bug</a>?
  1447. <br />
  1448. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1449. </div>
  1450. </body>
  1451. </html>
上海开阖软件有限公司 沪ICP备12045867号-1