isolating-extensions.html 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="Isolating Extension Modules" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/howto/isolating-extensions.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Abstract: Traditionally, state belonging to Python extension modules was kept in C static variables, which have process-wide scope. This document describes problems of such per-process state and sh..." />
  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="Abstract: Traditionally, state belonging to Python extension modules was kept in C static variables, which have process-wide scope. This document describes problems of such per-process state and sh..." />
  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>Isolating Extension Modules &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="Python Frequently Asked Questions" href="../faq/index.html" />
  34. <link rel="prev" title="Annotations Best Practices" href="annotations.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/howto/isolating-extensions.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.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="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="#">Isolating Extension Modules</a><ul>
  86. <li><a class="reference internal" href="#who-should-read-this">Who should read this</a></li>
  87. <li><a class="reference internal" href="#background">Background</a><ul>
  88. <li><a class="reference internal" href="#enter-per-module-state">Enter Per-Module State</a></li>
  89. <li><a class="reference internal" href="#isolated-module-objects">Isolated Module Objects</a></li>
  90. <li><a class="reference internal" href="#surprising-edge-cases">Surprising Edge Cases</a></li>
  91. </ul>
  92. </li>
  93. <li><a class="reference internal" href="#making-modules-safe-with-multiple-interpreters">Making Modules Safe with Multiple Interpreters</a><ul>
  94. <li><a class="reference internal" href="#managing-global-state">Managing Global State</a></li>
  95. <li><a class="reference internal" href="#managing-per-module-state">Managing Per-Module State</a></li>
  96. <li><a class="reference internal" href="#opt-out-limiting-to-one-module-object-per-process">Opt-Out: Limiting to One Module Object per Process</a></li>
  97. <li><a class="reference internal" href="#module-state-access-from-functions">Module State Access from Functions</a></li>
  98. </ul>
  99. </li>
  100. <li><a class="reference internal" href="#heap-types">Heap Types</a><ul>
  101. <li><a class="reference internal" href="#changing-static-types-to-heap-types">Changing Static Types to Heap Types</a></li>
  102. <li><a class="reference internal" href="#defining-heap-types">Defining Heap Types</a></li>
  103. <li><a class="reference internal" href="#garbage-collection-protocol">Garbage-Collection Protocol</a></li>
  104. <li><a class="reference internal" href="#module-state-access-from-classes">Module State Access from Classes</a></li>
  105. <li><a class="reference internal" href="#module-state-access-from-regular-methods">Module State Access from Regular Methods</a></li>
  106. <li><a class="reference internal" href="#module-state-access-from-slot-methods-getters-and-setters">Module State Access from Slot Methods, Getters and Setters</a></li>
  107. <li><a class="reference internal" href="#lifetime-of-the-module-state">Lifetime of the Module State</a></li>
  108. </ul>
  109. </li>
  110. <li><a class="reference internal" href="#open-issues">Open Issues</a><ul>
  111. <li><a class="reference internal" href="#per-class-scope">Per-Class Scope</a></li>
  112. <li><a class="reference internal" href="#lossless-conversion-to-heap-types">Lossless Conversion to Heap Types</a></li>
  113. </ul>
  114. </li>
  115. </ul>
  116. </li>
  117. </ul>
  118. </div>
  119. <div>
  120. <h4>Previous topic</h4>
  121. <p class="topless"><a href="annotations.html"
  122. title="previous chapter">Annotations Best Practices</a></p>
  123. </div>
  124. <div>
  125. <h4>Next topic</h4>
  126. <p class="topless"><a href="../faq/index.html"
  127. title="next chapter">Python Frequently Asked Questions</a></p>
  128. </div>
  129. <div role="note" aria-label="source link">
  130. <h3>This Page</h3>
  131. <ul class="this-page-menu">
  132. <li><a href="../bugs.html">Report a Bug</a></li>
  133. <li>
  134. <a href="https://github.com/python/cpython/blob/main/Doc/howto/isolating-extensions.rst"
  135. rel="nofollow">Show Source
  136. </a>
  137. </li>
  138. </ul>
  139. </div>
  140. </nav>
  141. </div>
  142. </div>
  143. <div class="related" role="navigation" aria-label="related navigation">
  144. <h3>Navigation</h3>
  145. <ul>
  146. <li class="right" style="margin-right: 10px">
  147. <a href="../genindex.html" title="General Index"
  148. accesskey="I">index</a></li>
  149. <li class="right" >
  150. <a href="../py-modindex.html" title="Python Module Index"
  151. >modules</a> |</li>
  152. <li class="right" >
  153. <a href="../faq/index.html" title="Python Frequently Asked Questions"
  154. accesskey="N">next</a> |</li>
  155. <li class="right" >
  156. <a href="annotations.html" title="Annotations Best Practices"
  157. accesskey="P">previous</a> |</li>
  158. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  159. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  160. <li class="switchers">
  161. <div class="language_switcher_placeholder"></div>
  162. <div class="version_switcher_placeholder"></div>
  163. </li>
  164. <li>
  165. </li>
  166. <li id="cpython-language-and-version">
  167. <a href="../index.html">3.12.0 Documentation</a> &#187;
  168. </li>
  169. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li>
  170. <li class="nav-item nav-item-this"><a href="">Isolating Extension Modules</a></li>
  171. <li class="right">
  172. <div class="inline-search" role="search">
  173. <form class="inline-search" action="../search.html" method="get">
  174. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  175. <input type="submit" value="Go" />
  176. </form>
  177. </div>
  178. |
  179. </li>
  180. <li class="right">
  181. <label class="theme-selector-label">
  182. Theme
  183. <select class="theme-selector" oninput="activateTheme(this.value)">
  184. <option value="auto" selected>Auto</option>
  185. <option value="light">Light</option>
  186. <option value="dark">Dark</option>
  187. </select>
  188. </label> |</li>
  189. </ul>
  190. </div>
  191. <div class="document">
  192. <div class="documentwrapper">
  193. <div class="bodywrapper">
  194. <div class="body" role="main">
  195. <section id="isolating-extension-modules">
  196. <span id="isolating-extensions-howto"></span><h1>Isolating Extension Modules<a class="headerlink" href="#isolating-extension-modules" title="Permalink to this headline">¶</a></h1>
  197. <div class="topic">
  198. <p class="topic-title">Abstract</p>
  199. <p>Traditionally, state belonging to Python extension modules was kept in C
  200. <code class="docutils literal notranslate"><span class="pre">static</span></code> variables, which have process-wide scope. This document
  201. describes problems of such per-process state and shows a safer way:
  202. per-module state.</p>
  203. <p>The document also describes how to switch to per-module state where
  204. possible. This transition involves allocating space for that state, potentially
  205. switching from static types to heap types, and—perhaps most
  206. importantly—accessing per-module state from code.</p>
  207. </div>
  208. <section id="who-should-read-this">
  209. <h2>Who should read this<a class="headerlink" href="#who-should-read-this" title="Permalink to this headline">¶</a></h2>
  210. <p>This guide is written for maintainers of <a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">C-API</span></a> extensions
  211. who would like to make that extension safer to use in applications where
  212. Python itself is used as a library.</p>
  213. </section>
  214. <section id="background">
  215. <h2>Background<a class="headerlink" href="#background" title="Permalink to this headline">¶</a></h2>
  216. <p>An <em>interpreter</em> is the context in which Python code runs. It contains
  217. configuration (e.g. the import path) and runtime state (e.g. the set of
  218. imported modules).</p>
  219. <p>Python supports running multiple interpreters in one process. There are
  220. two cases to think about—users may run interpreters:</p>
  221. <ul class="simple">
  222. <li><p>in sequence, with several <a class="reference internal" href="../c-api/init.html#c.Py_InitializeEx" title="Py_InitializeEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_InitializeEx()</span></code></a>/<a class="reference internal" href="../c-api/init.html#c.Py_FinalizeEx" title="Py_FinalizeEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_FinalizeEx()</span></code></a>
  223. cycles, and</p></li>
  224. <li><p>in parallel, managing “sub-interpreters” using
  225. <a class="reference internal" href="../c-api/init.html#c.Py_NewInterpreter" title="Py_NewInterpreter"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_NewInterpreter()</span></code></a>/<a class="reference internal" href="../c-api/init.html#c.Py_EndInterpreter" title="Py_EndInterpreter"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_EndInterpreter()</span></code></a>.</p></li>
  226. </ul>
  227. <p>Both cases (and combinations of them) would be most useful when
  228. embedding Python within a library. Libraries generally shouldn’t make
  229. assumptions about the application that uses them, which include
  230. assuming a process-wide “main Python interpreter”.</p>
  231. <p>Historically, Python extension modules don’t handle this use case well.
  232. Many extension modules (and even some stdlib modules) use <em>per-process</em>
  233. global state, because C <code class="docutils literal notranslate"><span class="pre">static</span></code> variables are extremely easy to use.
  234. Thus, data that should be specific to an interpreter ends up being shared
  235. between interpreters. Unless the extension developer is careful, it is very
  236. easy to introduce edge cases that lead to crashes when a module is loaded in
  237. more than one interpreter in the same process.</p>
  238. <p>Unfortunately, <em>per-interpreter</em> state is not easy to achieve. Extension
  239. authors tend to not keep multiple interpreters in mind when developing,
  240. and it is currently cumbersome to test the behavior.</p>
  241. <section id="enter-per-module-state">
  242. <h3>Enter Per-Module State<a class="headerlink" href="#enter-per-module-state" title="Permalink to this headline">¶</a></h3>
  243. <p>Instead of focusing on per-interpreter state, Python’s C API is evolving
  244. to better support the more granular <em>per-module</em> state.
  245. This means that C-level data should be attached to a <em>module object</em>.
  246. Each interpreter creates its own module object, keeping the data separate.
  247. For testing the isolation, multiple module objects corresponding to a single
  248. extension can even be loaded in a single interpreter.</p>
  249. <p>Per-module state provides an easy way to think about lifetime and
  250. resource ownership: the extension module will initialize when a
  251. module object is created, and clean up when it’s freed. In this regard,
  252. a module is just like any other <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>; there are no “on
  253. interpreter shutdown” hooks to think—or forget—about.</p>
  254. <p>Note that there are use cases for different kinds of “globals”:
  255. per-process, per-interpreter, per-thread or per-task state.
  256. With per-module state as the default, these are still possible,
  257. but you should treat them as exceptional cases:
  258. if you need them, you should give them additional care and testing.
  259. (Note that this guide does not cover them.)</p>
  260. </section>
  261. <section id="isolated-module-objects">
  262. <h3>Isolated Module Objects<a class="headerlink" href="#isolated-module-objects" title="Permalink to this headline">¶</a></h3>
  263. <p>The key point to keep in mind when developing an extension module is
  264. that several module objects can be created from a single shared library.
  265. For example:</p>
  266. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
  267. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">binascii</span>
  268. <span class="gp">&gt;&gt;&gt; </span><span class="n">old_binascii</span> <span class="o">=</span> <span class="n">binascii</span>
  269. <span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="s1">&#39;binascii&#39;</span><span class="p">]</span>
  270. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">binascii</span> <span class="c1"># create a new module object</span>
  271. <span class="gp">&gt;&gt;&gt; </span><span class="n">old_binascii</span> <span class="o">==</span> <span class="n">binascii</span>
  272. <span class="go">False</span>
  273. </pre></div>
  274. </div>
  275. <p>As a rule of thumb, the two modules should be completely independent.
  276. All objects and state specific to the module should be encapsulated
  277. within the module object, not shared with other module objects, and
  278. cleaned up when the module object is deallocated.
  279. Since this just is a rule of thumb, exceptions are possible
  280. (see <a class="reference internal" href="#managing-global-state">Managing Global State</a>), but they will need more
  281. thought and attention to edge cases.</p>
  282. <p>While some modules could do with less stringent restrictions, isolated
  283. modules make it easier to set clear expectations and guidelines that
  284. work across a variety of use cases.</p>
  285. </section>
  286. <section id="surprising-edge-cases">
  287. <h3>Surprising Edge Cases<a class="headerlink" href="#surprising-edge-cases" title="Permalink to this headline">¶</a></h3>
  288. <p>Note that isolated modules do create some surprising edge cases. Most
  289. notably, each module object will typically not share its classes and
  290. exceptions with other similar modules. Continuing from the
  291. <a class="reference internal" href="#isolated-module-objects">example above</a>,
  292. note that <code class="docutils literal notranslate"><span class="pre">old_binascii.Error</span></code> and <code class="docutils literal notranslate"><span class="pre">binascii.Error</span></code> are
  293. separate objects. In the following code, the exception is <em>not</em> caught:</p>
  294. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">old_binascii</span><span class="o">.</span><span class="n">Error</span> <span class="o">==</span> <span class="n">binascii</span><span class="o">.</span><span class="n">Error</span>
  295. <span class="go">False</span>
  296. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  297. <span class="gp">... </span> <span class="n">old_binascii</span><span class="o">.</span><span class="n">unhexlify</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;qwertyuiop&#39;</span><span class="p">)</span>
  298. <span class="gp">... </span><span class="k">except</span> <span class="n">binascii</span><span class="o">.</span><span class="n">Error</span><span class="p">:</span>
  299. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;boo&#39;</span><span class="p">)</span>
  300. <span class="gp">...</span>
  301. <span class="gt">Traceback (most recent call last):</span>
  302. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
  303. <span class="gr">binascii.Error</span>: <span class="n">Non-hexadecimal digit found</span>
  304. </pre></div>
  305. </div>
  306. <p>This is expected. Notice that pure-Python modules behave the same way:
  307. it is a part of how Python works.</p>
  308. <p>The goal is to make extension modules safe at the C level, not to make
  309. hacks behave intuitively. Mutating <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> “manually” counts
  310. as a hack.</p>
  311. </section>
  312. </section>
  313. <section id="making-modules-safe-with-multiple-interpreters">
  314. <h2>Making Modules Safe with Multiple Interpreters<a class="headerlink" href="#making-modules-safe-with-multiple-interpreters" title="Permalink to this headline">¶</a></h2>
  315. <section id="managing-global-state">
  316. <h3>Managing Global State<a class="headerlink" href="#managing-global-state" title="Permalink to this headline">¶</a></h3>
  317. <p>Sometimes, the state associated with a Python module is not specific to that module, but
  318. to the entire process (or something else “more global” than a module).
  319. For example:</p>
  320. <ul class="simple">
  321. <li><p>The <code class="docutils literal notranslate"><span class="pre">readline</span></code> module manages <em>the</em> terminal.</p></li>
  322. <li><p>A module running on a circuit board wants to control <em>the</em> on-board
  323. LED.</p></li>
  324. </ul>
  325. <p>In these cases, the Python module should provide <em>access</em> to the global
  326. state, rather than <em>own</em> it. If possible, write the module so that
  327. multiple copies of it can access the state independently (along with
  328. other libraries, whether for Python or other languages). If that is not
  329. possible, consider explicit locking.</p>
  330. <p>If it is necessary to use process-global state, the simplest way to
  331. avoid issues with multiple interpreters is to explicitly prevent a
  332. module from being loaded more than once per process—see
  333. <a class="reference internal" href="#opt-out-limiting-to-one-module-object-per-process">Opt-Out: Limiting to One Module Object per Process</a>.</p>
  334. </section>
  335. <section id="managing-per-module-state">
  336. <h3>Managing Per-Module State<a class="headerlink" href="#managing-per-module-state" title="Permalink to this headline">¶</a></h3>
  337. <p>To use per-module state, use
  338. <a class="reference internal" href="../c-api/module.html#multi-phase-initialization"><span class="std std-ref">multi-phase extension module initialization</span></a>.
  339. This signals that your module supports multiple interpreters correctly.</p>
  340. <p>Set <code class="docutils literal notranslate"><span class="pre">PyModuleDef.m_size</span></code> to a positive number to request that many
  341. bytes of storage local to the module. Usually, this will be set to the
  342. size of some module-specific <code class="docutils literal notranslate"><span class="pre">struct</span></code>, which can store all of the
  343. module’s C-level state. In particular, it is where you should put
  344. pointers to classes (including exceptions, but excluding static types)
  345. and settings (e.g. <code class="docutils literal notranslate"><span class="pre">csv</span></code>’s <a class="reference internal" href="../library/csv.html#csv.field_size_limit" title="csv.field_size_limit"><code class="xref py py-data docutils literal notranslate"><span class="pre">field_size_limit</span></code></a>)
  346. which the C code needs to function.</p>
  347. <div class="admonition note">
  348. <p class="admonition-title">Note</p>
  349. <p>Another option is to store state in the module’s <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>,
  350. but you must avoid crashing when users modify <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> from
  351. Python code. This usually means error- and type-checking at the C level,
  352. which is easy to get wrong and hard to test sufficiently.</p>
  353. <p>However, if module state is not needed in C code, storing it in
  354. <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> only is a good idea.</p>
  355. </div>
  356. <p>If the module state includes <code class="docutils literal notranslate"><span class="pre">PyObject</span></code> pointers, the module object
  357. must hold references to those objects and implement the module-level hooks
  358. <code class="docutils literal notranslate"><span class="pre">m_traverse</span></code>, <code class="docutils literal notranslate"><span class="pre">m_clear</span></code> and <code class="docutils literal notranslate"><span class="pre">m_free</span></code>. These work like
  359. <code class="docutils literal notranslate"><span class="pre">tp_traverse</span></code>, <code class="docutils literal notranslate"><span class="pre">tp_clear</span></code> and <code class="docutils literal notranslate"><span class="pre">tp_free</span></code> of a class. Adding them will
  360. require some work and make the code longer; this is the price for
  361. modules which can be unloaded cleanly.</p>
  362. <p>An example of a module with per-module state is currently available as
  363. <a class="reference external" href="https://github.com/python/cpython/blob/master/Modules/xxlimited.c">xxlimited</a>;
  364. example module initialization shown at the bottom of the file.</p>
  365. </section>
  366. <section id="opt-out-limiting-to-one-module-object-per-process">
  367. <h3>Opt-Out: Limiting to One Module Object per Process<a class="headerlink" href="#opt-out-limiting-to-one-module-object-per-process" title="Permalink to this headline">¶</a></h3>
  368. <p>A non-negative <code class="docutils literal notranslate"><span class="pre">PyModuleDef.m_size</span></code> signals that a module supports
  369. multiple interpreters correctly. If this is not yet the case for your
  370. module, you can explicitly make your module loadable only once per
  371. process. For example:</p>
  372. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">loaded</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
  373. <span class="k">static</span><span class="w"> </span><span class="kt">int</span>
  374. <span class="nf">exec_module</span><span class="p">(</span><span class="n">PyObject</span><span class="o">*</span><span class="w"> </span><span class="n">module</span><span class="p">)</span>
  375. <span class="p">{</span>
  376. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">loaded</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  377. <span class="w"> </span><span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_ImportError</span><span class="p">,</span>
  378. <span class="w"> </span><span class="s">&quot;cannot load module more than once per process&quot;</span><span class="p">);</span>
  379. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mi">-1</span><span class="p">;</span>
  380. <span class="w"> </span><span class="p">}</span>
  381. <span class="w"> </span><span class="n">loaded</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span>
  382. <span class="w"> </span><span class="c1">// ... rest of initialization</span>
  383. <span class="p">}</span>
  384. </pre></div>
  385. </div>
  386. </section>
  387. <section id="module-state-access-from-functions">
  388. <h3>Module State Access from Functions<a class="headerlink" href="#module-state-access-from-functions" title="Permalink to this headline">¶</a></h3>
  389. <p>Accessing the state from module-level functions is straightforward.
  390. Functions get the module object as their first argument; for extracting
  391. the state, you can use <code class="docutils literal notranslate"><span class="pre">PyModule_GetState</span></code>:</p>
  392. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  393. <span class="nf">func</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">module</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
  394. <span class="p">{</span>
  395. <span class="w"> </span><span class="n">my_struct</span><span class="w"> </span><span class="o">*</span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">my_struct</span><span class="o">*</span><span class="p">)</span><span class="n">PyModule_GetState</span><span class="p">(</span><span class="n">module</span><span class="p">);</span>
  396. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">state</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  397. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  398. <span class="w"> </span><span class="p">}</span>
  399. <span class="w"> </span><span class="c1">// ... rest of logic</span>
  400. <span class="p">}</span>
  401. </pre></div>
  402. </div>
  403. <div class="admonition note">
  404. <p class="admonition-title">Note</p>
  405. <p><code class="docutils literal notranslate"><span class="pre">PyModule_GetState</span></code> may return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> without setting an
  406. exception if there is no module state, i.e. <code class="docutils literal notranslate"><span class="pre">PyModuleDef.m_size</span></code> was
  407. zero. In your own module, you’re in control of <code class="docutils literal notranslate"><span class="pre">m_size</span></code>, so this is
  408. easy to prevent.</p>
  409. </div>
  410. </section>
  411. </section>
  412. <section id="heap-types">
  413. <h2>Heap Types<a class="headerlink" href="#heap-types" title="Permalink to this headline">¶</a></h2>
  414. <p>Traditionally, types defined in C code are <em>static</em>; that is,
  415. <code class="docutils literal notranslate"><span class="pre">static</span> <span class="pre">PyTypeObject</span></code> structures defined directly in code and
  416. initialized using <code class="docutils literal notranslate"><span class="pre">PyType_Ready()</span></code>.</p>
  417. <p>Such types are necessarily shared across the process. Sharing them
  418. between module objects requires paying attention to any state they own
  419. or access. To limit the possible issues, static types are immutable at
  420. the Python level: for example, you can’t set <code class="docutils literal notranslate"><span class="pre">str.myattribute</span> <span class="pre">=</span> <span class="pre">123</span></code>.</p>
  421. <div class="impl-detail compound">
  422. <p><strong>CPython implementation detail:</strong> Sharing truly immutable objects between interpreters is fine,
  423. as long as they don’t provide access to mutable objects.
  424. However, in CPython, every Python object has a mutable implementation
  425. detail: the reference count. Changes to the refcount are guarded by the GIL.
  426. Thus, code that shares any Python objects across interpreters implicitly
  427. depends on CPython’s current, process-wide GIL.</p>
  428. </div>
  429. <p>Because they are immutable and process-global, static types cannot access
  430. “their” module state.
  431. If any method of such a type requires access to module state,
  432. the type must be converted to a <em>heap-allocated type</em>, or <em>heap type</em>
  433. for short. These correspond more closely to classes created by Python’s
  434. <code class="docutils literal notranslate"><span class="pre">class</span></code> statement.</p>
  435. <p>For new modules, using heap types by default is a good rule of thumb.</p>
  436. <section id="changing-static-types-to-heap-types">
  437. <h3>Changing Static Types to Heap Types<a class="headerlink" href="#changing-static-types-to-heap-types" title="Permalink to this headline">¶</a></h3>
  438. <p>Static types can be converted to heap types, but note that
  439. the heap type API was not designed for “lossless” conversion
  440. from static types—that is, creating a type that works exactly like a given
  441. static type.
  442. So, when rewriting the class definition in a new API,
  443. you are likely to unintentionally change a few details (e.g. pickleability
  444. or inherited slots).
  445. Always test the details that are important to you.</p>
  446. <p>Watch out for the following two points in particular (but note that this is not
  447. a comprehensive list):</p>
  448. <ul class="simple">
  449. <li><p>Unlike static types, heap type objects are mutable by default.
  450. Use the <a class="reference internal" href="../c-api/typeobj.html#c.Py_TPFLAGS_IMMUTABLETYPE" title="Py_TPFLAGS_IMMUTABLETYPE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_IMMUTABLETYPE</span></code></a> flag to prevent mutability.</p></li>
  451. <li><p>Heap types inherit <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> by default,
  452. so it may become possible to instantiate them from Python code.
  453. You can prevent this with the <a class="reference internal" href="../c-api/typeobj.html#c.Py_TPFLAGS_DISALLOW_INSTANTIATION" title="Py_TPFLAGS_DISALLOW_INSTANTIATION"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_DISALLOW_INSTANTIATION</span></code></a> flag.</p></li>
  454. </ul>
  455. </section>
  456. <section id="defining-heap-types">
  457. <h3>Defining Heap Types<a class="headerlink" href="#defining-heap-types" title="Permalink to this headline">¶</a></h3>
  458. <p>Heap types can be created by filling a <a class="reference internal" href="../c-api/type.html#c.PyType_Spec" title="PyType_Spec"><code class="xref c c-struct docutils literal notranslate"><span class="pre">PyType_Spec</span></code></a> structure, a
  459. description or “blueprint” of a class, and calling
  460. <a class="reference internal" href="../c-api/type.html#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_FromModuleAndSpec()</span></code></a> to construct a new class object.</p>
  461. <div class="admonition note">
  462. <p class="admonition-title">Note</p>
  463. <p>Other functions, like <a class="reference internal" href="../c-api/type.html#c.PyType_FromSpec" title="PyType_FromSpec"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_FromSpec()</span></code></a>, can also create
  464. heap types, but <a class="reference internal" href="../c-api/type.html#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_FromModuleAndSpec()</span></code></a> associates the module
  465. with the class, allowing access to the module state from methods.</p>
  466. </div>
  467. <p>The class should generally be stored in <em>both</em> the module state (for
  468. safe access from C) and the module’s <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> (for access from
  469. Python code).</p>
  470. </section>
  471. <section id="garbage-collection-protocol">
  472. <h3>Garbage-Collection Protocol<a class="headerlink" href="#garbage-collection-protocol" title="Permalink to this headline">¶</a></h3>
  473. <p>Instances of heap types hold a reference to their type.
  474. This ensures that the type isn’t destroyed before all its instances are,
  475. but may result in reference cycles that need to be broken by the
  476. garbage collector.</p>
  477. <p>To avoid memory leaks, instances of heap types must implement the
  478. garbage collection protocol.
  479. That is, heap types should:</p>
  480. <ul class="simple">
  481. <li><p>Have the <a class="reference internal" href="../c-api/typeobj.html#c.Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag.</p></li>
  482. <li><p>Define a traverse function using <code class="docutils literal notranslate"><span class="pre">Py_tp_traverse</span></code>, which
  483. visits the type (e.g. using <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/gcsupport.html#c.Py_VISIT" title="Py_VISIT"><span class="n">Py_VISIT</span></a><span class="p">(</span><a class="reference internal" href="../c-api/structures.html#c.Py_TYPE" title="Py_TYPE"><span class="n">Py_TYPE</span></a><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="p">)</span></span>).</p></li>
  484. </ul>
  485. <p>Please refer to the <a class="reference internal" href="../c-api/typeobj.html#type-structs"><span class="std std-ref">the documentation</span></a> of
  486. <a class="reference internal" href="../c-api/typeobj.html#c.Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> and <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a>
  487. for additional considerations.</p>
  488. <p>If your traverse function delegates to the <code class="docutils literal notranslate"><span class="pre">tp_traverse</span></code> of its base class
  489. (or another type), ensure that <code class="docutils literal notranslate"><span class="pre">Py_TYPE(self)</span></code> is visited only once.
  490. Note that only heap type are expected to visit the type in <code class="docutils literal notranslate"><span class="pre">tp_traverse</span></code>.</p>
  491. <p>For example, if your traverse function includes:</p>
  492. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">base</span><span class="o">-&gt;</span><span class="n">tp_traverse</span><span class="p">(</span><span class="n">self</span><span class="p">,</span><span class="w"> </span><span class="n">visit</span><span class="p">,</span><span class="w"> </span><span class="n">arg</span><span class="p">)</span>
  493. </pre></div>
  494. </div>
  495. <p>…and <code class="docutils literal notranslate"><span class="pre">base</span></code> may be a static type, then it should also include:</p>
  496. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">base</span><span class="o">-&gt;</span><span class="n">tp_flags</span><span class="w"> </span><span class="o">&amp;</span><span class="w"> </span><span class="n">Py_TPFLAGS_HEAPTYPE</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  497. <span class="w"> </span><span class="c1">// a heap type&#39;s tp_traverse already visited Py_TYPE(self)</span>
  498. <span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
  499. <span class="w"> </span><span class="n">Py_VISIT</span><span class="p">(</span><span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">));</span>
  500. <span class="p">}</span>
  501. </pre></div>
  502. </div>
  503. <p>It is not necessary to handle the type’s reference count in <code class="docutils literal notranslate"><span class="pre">tp_new</span></code>
  504. and <code class="docutils literal notranslate"><span class="pre">tp_clear</span></code>.</p>
  505. </section>
  506. <section id="module-state-access-from-classes">
  507. <h3>Module State Access from Classes<a class="headerlink" href="#module-state-access-from-classes" title="Permalink to this headline">¶</a></h3>
  508. <p>If you have a type object defined with <a class="reference internal" href="../c-api/type.html#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_FromModuleAndSpec()</span></code></a>,
  509. you can call <a class="reference internal" href="../c-api/type.html#c.PyType_GetModule" title="PyType_GetModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GetModule()</span></code></a> to get the associated module, and then
  510. <a class="reference internal" href="../c-api/module.html#c.PyModule_GetState" title="PyModule_GetState"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_GetState()</span></code></a> to get the module’s state.</p>
  511. <p>To save a some tedious error-handling boilerplate code, you can combine
  512. these two steps with <a class="reference internal" href="../c-api/type.html#c.PyType_GetModuleState" title="PyType_GetModuleState"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GetModuleState()</span></code></a>, resulting in:</p>
  513. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">my_struct</span><span class="w"> </span><span class="o">*</span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">my_struct</span><span class="o">*</span><span class="p">)</span><span class="n">PyType_GetModuleState</span><span class="p">(</span><span class="n">type</span><span class="p">);</span>
  514. <span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">state</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  515. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  516. <span class="p">}</span>
  517. </pre></div>
  518. </div>
  519. </section>
  520. <section id="module-state-access-from-regular-methods">
  521. <h3>Module State Access from Regular Methods<a class="headerlink" href="#module-state-access-from-regular-methods" title="Permalink to this headline">¶</a></h3>
  522. <p>Accessing the module-level state from methods of a class is somewhat more
  523. complicated, but is possible thanks to API introduced in Python 3.9.
  524. To get the state, you need to first get the <em>defining class</em>, and then
  525. get the module state from it.</p>
  526. <p>The largest roadblock is getting <em>the class a method was defined in</em>, or
  527. that method’s “defining class” for short. The defining class can have a
  528. reference to the module it is part of.</p>
  529. <p>Do not confuse the defining class with <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures.html#c.Py_TYPE" title="Py_TYPE"><span class="n">Py_TYPE</span></a><span class="p">(</span><span class="n">self</span><span class="p">)</span></span>. If the method
  530. is called on a <em>subclass</em> of your type, <code class="docutils literal notranslate"><span class="pre">Py_TYPE(self)</span></code> will refer to
  531. that subclass, which may be defined in different module than yours.</p>
  532. <div class="admonition note">
  533. <p class="admonition-title">Note</p>
  534. <p>The following Python code can illustrate the concept.
  535. <code class="docutils literal notranslate"><span class="pre">Base.get_defining_class</span></code> returns <code class="docutils literal notranslate"><span class="pre">Base</span></code> even
  536. if <code class="docutils literal notranslate"><span class="pre">type(self)</span> <span class="pre">==</span> <span class="pre">Sub</span></code>:</p>
  537. <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Base</span><span class="p">:</span>
  538. <span class="k">def</span> <span class="nf">get_type_of_self</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  539. <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
  540. <span class="k">def</span> <span class="nf">get_defining_class</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  541. <span class="k">return</span> <span class="vm">__class__</span>
  542. <span class="k">class</span> <span class="nc">Sub</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
  543. <span class="k">pass</span>
  544. </pre></div>
  545. </div>
  546. </div>
  547. <p>For a method to get its “defining class”, it must use the
  548. <a class="reference internal" href="../c-api/structures.html#meth-method-meth-fastcall-meth-keywords"><span class="std std-ref">METH_METHOD | METH_FASTCALL | METH_KEYWORDS</span></a>
  549. <a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">calling</span> <span class="pre">convention</span></code></a>
  550. and the corresponding <a class="reference internal" href="../c-api/structures.html#c.PyCMethod" title="PyCMethod"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCMethod</span></code></a> signature:</p>
  551. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">PyCMethod</span><span class="p">(</span>
  552. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">self</span><span class="p">,</span><span class="w"> </span><span class="c1">// object the method was called on</span>
  553. <span class="w"> </span><span class="n">PyTypeObject</span><span class="w"> </span><span class="o">*</span><span class="n">defining_class</span><span class="p">,</span><span class="w"> </span><span class="c1">// defining class</span>
  554. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="c1">// C array of arguments</span>
  555. <span class="w"> </span><span class="n">Py_ssize_t</span><span class="w"> </span><span class="n">nargs</span><span class="p">,</span><span class="w"> </span><span class="c1">// length of &quot;args&quot;</span>
  556. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">kwnames</span><span class="p">)</span><span class="w"> </span><span class="c1">// NULL, or dict of keyword arguments</span>
  557. </pre></div>
  558. </div>
  559. <p>Once you have the defining class, call <a class="reference internal" href="../c-api/type.html#c.PyType_GetModuleState" title="PyType_GetModuleState"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GetModuleState()</span></code></a> to get
  560. the state of its associated module.</p>
  561. <p>For example:</p>
  562. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  563. <span class="nf">example_method</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">self</span><span class="p">,</span>
  564. <span class="w"> </span><span class="n">PyTypeObject</span><span class="w"> </span><span class="o">*</span><span class="n">defining_class</span><span class="p">,</span>
  565. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">,</span>
  566. <span class="w"> </span><span class="n">Py_ssize_t</span><span class="w"> </span><span class="n">nargs</span><span class="p">,</span>
  567. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">kwnames</span><span class="p">)</span>
  568. <span class="p">{</span>
  569. <span class="w"> </span><span class="n">my_struct</span><span class="w"> </span><span class="o">*</span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">my_struct</span><span class="o">*</span><span class="p">)</span><span class="n">PyType_GetModuleState</span><span class="p">(</span><span class="n">defining_class</span><span class="p">);</span>
  570. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">state</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  571. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  572. <span class="w"> </span><span class="p">}</span>
  573. <span class="w"> </span><span class="p">...</span><span class="w"> </span><span class="c1">// rest of logic</span>
  574. <span class="p">}</span>
  575. <span class="n">PyDoc_STRVAR</span><span class="p">(</span><span class="n">example_method_doc</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;...&quot;</span><span class="p">);</span>
  576. <span class="k">static</span><span class="w"> </span><span class="n">PyMethodDef</span><span class="w"> </span><span class="n">my_methods</span><span class="p">[]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
  577. <span class="w"> </span><span class="p">{</span><span class="s">&quot;example_method&quot;</span><span class="p">,</span>
  578. <span class="w"> </span><span class="p">(</span><span class="n">PyCFunction</span><span class="p">)(</span><span class="kt">void</span><span class="p">(</span><span class="o">*</span><span class="p">)(</span><span class="kt">void</span><span class="p">))</span><span class="n">example_method</span><span class="p">,</span>
  579. <span class="w"> </span><span class="n">METH_METHOD</span><span class="o">|</span><span class="n">METH_FASTCALL</span><span class="o">|</span><span class="n">METH_KEYWORDS</span><span class="p">,</span>
  580. <span class="w"> </span><span class="n">example_method_doc</span><span class="p">}</span>
  581. <span class="w"> </span><span class="p">{</span><span class="nb">NULL</span><span class="p">},</span>
  582. <span class="p">}</span>
  583. </pre></div>
  584. </div>
  585. </section>
  586. <section id="module-state-access-from-slot-methods-getters-and-setters">
  587. <h3>Module State Access from Slot Methods, Getters and Setters<a class="headerlink" href="#module-state-access-from-slot-methods-getters-and-setters" title="Permalink to this headline">¶</a></h3>
  588. <div class="admonition note">
  589. <p class="admonition-title">Note</p>
  590. <p>This is new in Python 3.11.</p>
  591. </div>
  592. <p>Slot methods—the fast C equivalents for special methods, such as
  593. <a class="reference internal" href="../c-api/typeobj.html#c.PyNumberMethods.nb_add" title="PyNumberMethods.nb_add"><code class="xref c c-member docutils literal notranslate"><span class="pre">nb_add</span></code></a> for <a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__add__</span></code></a> or
  594. <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> for initialization—have a very simple API that
  595. doesn’t allow passing in the defining class, unlike with <a class="reference internal" href="../c-api/structures.html#c.PyCMethod" title="PyCMethod"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCMethod</span></code></a>.
  596. The same goes for getters and setters defined with
  597. <a class="reference internal" href="../c-api/structures.html#c.PyGetSetDef" title="PyGetSetDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyGetSetDef</span></code></a>.</p>
  598. <p>To access the module state in these cases, use the
  599. <a class="reference internal" href="../c-api/type.html#c.PyType_GetModuleByDef" title="PyType_GetModuleByDef"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GetModuleByDef()</span></code></a> function, and pass in the module definition.
  600. Once you have the module, call <a class="reference internal" href="../c-api/module.html#c.PyModule_GetState" title="PyModule_GetState"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_GetState()</span></code></a>
  601. to get the state:</p>
  602. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">module</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyType_GetModuleByDef</span><span class="p">(</span><span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">),</span><span class="w"> </span><span class="o">&amp;</span><span class="n">module_def</span><span class="p">);</span>
  603. <span class="n">my_struct</span><span class="w"> </span><span class="o">*</span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="n">my_struct</span><span class="o">*</span><span class="p">)</span><span class="n">PyModule_GetState</span><span class="p">(</span><span class="n">module</span><span class="p">);</span>
  604. <span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">state</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  605. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  606. <span class="p">}</span>
  607. </pre></div>
  608. </div>
  609. <p><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GetModuleByDef()</span></code> works by searching the
  610. <a class="reference internal" href="../glossary.html#term-method-resolution-order"><span class="xref std std-term">method resolution order</span></a> (i.e. all superclasses) for the first
  611. superclass that has a corresponding module.</p>
  612. <div class="admonition note">
  613. <p class="admonition-title">Note</p>
  614. <p>In very exotic cases (inheritance chains spanning multiple modules
  615. created from the same definition), <code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GetModuleByDef()</span></code> might not
  616. return the module of the true defining class. However, it will always
  617. return a module with the same definition, ensuring a compatible
  618. C memory layout.</p>
  619. </div>
  620. </section>
  621. <section id="lifetime-of-the-module-state">
  622. <h3>Lifetime of the Module State<a class="headerlink" href="#lifetime-of-the-module-state" title="Permalink to this headline">¶</a></h3>
  623. <p>When a module object is garbage-collected, its module state is freed.
  624. For each pointer to (a part of) the module state, you must hold a reference
  625. to the module object.</p>
  626. <p>Usually this is not an issue, because types created with
  627. <a class="reference internal" href="../c-api/type.html#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_FromModuleAndSpec()</span></code></a>, and their instances, hold a reference
  628. to the module.
  629. However, you must be careful in reference counting when you reference
  630. module state from other places, such as callbacks for external
  631. libraries.</p>
  632. </section>
  633. </section>
  634. <section id="open-issues">
  635. <h2>Open Issues<a class="headerlink" href="#open-issues" title="Permalink to this headline">¶</a></h2>
  636. <p>Several issues around per-module state and heap types are still open.</p>
  637. <p>Discussions about improving the situation are best held on the <a class="reference external" href="https://mail.python.org/mailman3/lists/capi-sig.python.org/">capi-sig
  638. mailing list</a>.</p>
  639. <section id="per-class-scope">
  640. <h3>Per-Class Scope<a class="headerlink" href="#per-class-scope" title="Permalink to this headline">¶</a></h3>
  641. <p>It is currently (as of Python 3.11) not possible to attach state to individual
  642. <em>types</em> without relying on CPython implementation details (which may change
  643. in the future—perhaps, ironically, to allow a proper solution for
  644. per-class scope).</p>
  645. </section>
  646. <section id="lossless-conversion-to-heap-types">
  647. <h3>Lossless Conversion to Heap Types<a class="headerlink" href="#lossless-conversion-to-heap-types" title="Permalink to this headline">¶</a></h3>
  648. <p>The heap type API was not designed for “lossless” conversion from static types;
  649. that is, creating a type that works exactly like a given static type.</p>
  650. </section>
  651. </section>
  652. </section>
  653. <div class="clearer"></div>
  654. </div>
  655. </div>
  656. </div>
  657. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  658. <div class="sphinxsidebarwrapper">
  659. <div>
  660. <h3><a href="../contents.html">Table of Contents</a></h3>
  661. <ul>
  662. <li><a class="reference internal" href="#">Isolating Extension Modules</a><ul>
  663. <li><a class="reference internal" href="#who-should-read-this">Who should read this</a></li>
  664. <li><a class="reference internal" href="#background">Background</a><ul>
  665. <li><a class="reference internal" href="#enter-per-module-state">Enter Per-Module State</a></li>
  666. <li><a class="reference internal" href="#isolated-module-objects">Isolated Module Objects</a></li>
  667. <li><a class="reference internal" href="#surprising-edge-cases">Surprising Edge Cases</a></li>
  668. </ul>
  669. </li>
  670. <li><a class="reference internal" href="#making-modules-safe-with-multiple-interpreters">Making Modules Safe with Multiple Interpreters</a><ul>
  671. <li><a class="reference internal" href="#managing-global-state">Managing Global State</a></li>
  672. <li><a class="reference internal" href="#managing-per-module-state">Managing Per-Module State</a></li>
  673. <li><a class="reference internal" href="#opt-out-limiting-to-one-module-object-per-process">Opt-Out: Limiting to One Module Object per Process</a></li>
  674. <li><a class="reference internal" href="#module-state-access-from-functions">Module State Access from Functions</a></li>
  675. </ul>
  676. </li>
  677. <li><a class="reference internal" href="#heap-types">Heap Types</a><ul>
  678. <li><a class="reference internal" href="#changing-static-types-to-heap-types">Changing Static Types to Heap Types</a></li>
  679. <li><a class="reference internal" href="#defining-heap-types">Defining Heap Types</a></li>
  680. <li><a class="reference internal" href="#garbage-collection-protocol">Garbage-Collection Protocol</a></li>
  681. <li><a class="reference internal" href="#module-state-access-from-classes">Module State Access from Classes</a></li>
  682. <li><a class="reference internal" href="#module-state-access-from-regular-methods">Module State Access from Regular Methods</a></li>
  683. <li><a class="reference internal" href="#module-state-access-from-slot-methods-getters-and-setters">Module State Access from Slot Methods, Getters and Setters</a></li>
  684. <li><a class="reference internal" href="#lifetime-of-the-module-state">Lifetime of the Module State</a></li>
  685. </ul>
  686. </li>
  687. <li><a class="reference internal" href="#open-issues">Open Issues</a><ul>
  688. <li><a class="reference internal" href="#per-class-scope">Per-Class Scope</a></li>
  689. <li><a class="reference internal" href="#lossless-conversion-to-heap-types">Lossless Conversion to Heap Types</a></li>
  690. </ul>
  691. </li>
  692. </ul>
  693. </li>
  694. </ul>
  695. </div>
  696. <div>
  697. <h4>Previous topic</h4>
  698. <p class="topless"><a href="annotations.html"
  699. title="previous chapter">Annotations Best Practices</a></p>
  700. </div>
  701. <div>
  702. <h4>Next topic</h4>
  703. <p class="topless"><a href="../faq/index.html"
  704. title="next chapter">Python Frequently Asked Questions</a></p>
  705. </div>
  706. <div role="note" aria-label="source link">
  707. <h3>This Page</h3>
  708. <ul class="this-page-menu">
  709. <li><a href="../bugs.html">Report a Bug</a></li>
  710. <li>
  711. <a href="https://github.com/python/cpython/blob/main/Doc/howto/isolating-extensions.rst"
  712. rel="nofollow">Show Source
  713. </a>
  714. </li>
  715. </ul>
  716. </div>
  717. </div>
  718. </div>
  719. <div class="clearer"></div>
  720. </div>
  721. <div class="related" role="navigation" aria-label="related navigation">
  722. <h3>Navigation</h3>
  723. <ul>
  724. <li class="right" style="margin-right: 10px">
  725. <a href="../genindex.html" title="General Index"
  726. >index</a></li>
  727. <li class="right" >
  728. <a href="../py-modindex.html" title="Python Module Index"
  729. >modules</a> |</li>
  730. <li class="right" >
  731. <a href="../faq/index.html" title="Python Frequently Asked Questions"
  732. >next</a> |</li>
  733. <li class="right" >
  734. <a href="annotations.html" title="Annotations Best Practices"
  735. >previous</a> |</li>
  736. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  737. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  738. <li class="switchers">
  739. <div class="language_switcher_placeholder"></div>
  740. <div class="version_switcher_placeholder"></div>
  741. </li>
  742. <li>
  743. </li>
  744. <li id="cpython-language-and-version">
  745. <a href="../index.html">3.12.0 Documentation</a> &#187;
  746. </li>
  747. <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
  748. <li class="nav-item nav-item-this"><a href="">Isolating Extension Modules</a></li>
  749. <li class="right">
  750. <div class="inline-search" role="search">
  751. <form class="inline-search" action="../search.html" method="get">
  752. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  753. <input type="submit" value="Go" />
  754. </form>
  755. </div>
  756. |
  757. </li>
  758. <li class="right">
  759. <label class="theme-selector-label">
  760. Theme
  761. <select class="theme-selector" oninput="activateTheme(this.value)">
  762. <option value="auto" selected>Auto</option>
  763. <option value="light">Light</option>
  764. <option value="dark">Dark</option>
  765. </select>
  766. </label> |</li>
  767. </ul>
  768. </div>
  769. <div class="footer">
  770. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  771. <br />
  772. This page is licensed under the Python Software Foundation License Version 2.
  773. <br />
  774. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  775. <br />
  776. See <a href="/license.html">History and License</a> for more information.<br />
  777. <br />
  778. The Python Software Foundation is a non-profit corporation.
  779. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  780. <br />
  781. <br />
  782. Last updated on Oct 02, 2023.
  783. <a href="/bugs.html">Found a bug</a>?
  784. <br />
  785. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  786. </div>
  787. </body>
  788. </html>