diff options
| author | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
|---|---|---|
| committer | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
| commit | 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch) | |
| tree | f1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/howto%2Fisolating-extensions.html | |
new repository
Diffstat (limited to 'devdocs/python~3.12/howto%2Fisolating-extensions.html')
| -rw-r--r-- | devdocs/python~3.12/howto%2Fisolating-extensions.html | 128 |
1 files changed, 128 insertions, 0 deletions
diff --git a/devdocs/python~3.12/howto%2Fisolating-extensions.html b/devdocs/python~3.12/howto%2Fisolating-extensions.html new file mode 100644 index 00000000..e9d8d15c --- /dev/null +++ b/devdocs/python~3.12/howto%2Fisolating-extensions.html @@ -0,0 +1,128 @@ + <span id="isolating-extensions-howto"></span><h1>Isolating Extension Modules</h1> <div class="topic"> <p class="topic-title">Abstract</p> <p>Traditionally, state belonging to Python extension modules was kept in C <code>static</code> variables, which have process-wide scope. This document describes problems of such per-process state and shows a safer way: per-module state.</p> <p>The document also describes how to switch to per-module state where possible. This transition involves allocating space for that state, potentially switching from static types to heap types, and—perhaps most importantly—accessing per-module state from code.</p> </div> <section id="who-should-read-this"> <h2>Who should read this</h2> <p>This guide is written for maintainers of <a class="reference internal" href="../c-api/index#c-api-index"><span class="std std-ref">C-API</span></a> extensions who would like to make that extension safer to use in applications where Python itself is used as a library.</p> </section> <section id="background"> <h2>Background</h2> <p>An <em>interpreter</em> is the context in which Python code runs. It contains configuration (e.g. the import path) and runtime state (e.g. the set of imported modules).</p> <p>Python supports running multiple interpreters in one process. There are two cases to think about—users may run interpreters:</p> <ul class="simple"> <li>in sequence, with several <a class="reference internal" href="../c-api/init#c.Py_InitializeEx" title="Py_InitializeEx"><code>Py_InitializeEx()</code></a>/<a class="reference internal" href="../c-api/init#c.Py_FinalizeEx" title="Py_FinalizeEx"><code>Py_FinalizeEx()</code></a> cycles, and</li> <li>in parallel, managing “sub-interpreters” using <a class="reference internal" href="../c-api/init#c.Py_NewInterpreter" title="Py_NewInterpreter"><code>Py_NewInterpreter()</code></a>/<a class="reference internal" href="../c-api/init#c.Py_EndInterpreter" title="Py_EndInterpreter"><code>Py_EndInterpreter()</code></a>.</li> </ul> <p>Both cases (and combinations of them) would be most useful when embedding Python within a library. Libraries generally shouldn’t make assumptions about the application that uses them, which include assuming a process-wide “main Python interpreter”.</p> <p>Historically, Python extension modules don’t handle this use case well. Many extension modules (and even some stdlib modules) use <em>per-process</em> global state, because C <code>static</code> variables are extremely easy to use. Thus, data that should be specific to an interpreter ends up being shared between interpreters. Unless the extension developer is careful, it is very easy to introduce edge cases that lead to crashes when a module is loaded in more than one interpreter in the same process.</p> <p>Unfortunately, <em>per-interpreter</em> state is not easy to achieve. Extension authors tend to not keep multiple interpreters in mind when developing, and it is currently cumbersome to test the behavior.</p> <section id="enter-per-module-state"> <h3>Enter Per-Module State</h3> <p>Instead of focusing on per-interpreter state, Python’s C API is evolving to better support the more granular <em>per-module</em> state. This means that C-level data should be attached to a <em>module object</em>. Each interpreter creates its own module object, keeping the data separate. For testing the isolation, multiple module objects corresponding to a single extension can even be loaded in a single interpreter.</p> <p>Per-module state provides an easy way to think about lifetime and resource ownership: the extension module will initialize when a module object is created, and clean up when it’s freed. In this regard, a module is just like any other <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>; there are no “on interpreter shutdown” hooks to think—or forget—about.</p> <p>Note that there are use cases for different kinds of “globals”: per-process, per-interpreter, per-thread or per-task state. With per-module state as the default, these are still possible, but you should treat them as exceptional cases: if you need them, you should give them additional care and testing. (Note that this guide does not cover them.)</p> </section> <section id="isolated-module-objects"> <h3>Isolated Module Objects</h3> <p>The key point to keep in mind when developing an extension module is that several module objects can be created from a single shared library. For example:</p> <pre data-language="pycon">>>> import sys +>>> import binascii +>>> old_binascii = binascii +>>> del sys.modules['binascii'] +>>> import binascii # create a new module object +>>> old_binascii == binascii +False +</pre> <p>As a rule of thumb, the two modules should be completely independent. All objects and state specific to the module should be encapsulated within the module object, not shared with other module objects, and cleaned up when the module object is deallocated. Since this just is a rule of thumb, exceptions are possible (see <a class="reference internal" href="#managing-global-state">Managing Global State</a>), but they will need more thought and attention to edge cases.</p> <p>While some modules could do with less stringent restrictions, isolated modules make it easier to set clear expectations and guidelines that work across a variety of use cases.</p> </section> <section id="surprising-edge-cases"> <h3>Surprising Edge Cases</h3> <p>Note that isolated modules do create some surprising edge cases. Most notably, each module object will typically not share its classes and exceptions with other similar modules. Continuing from the <a class="reference internal" href="#isolated-module-objects">example above</a>, note that <code>old_binascii.Error</code> and <code>binascii.Error</code> are separate objects. In the following code, the exception is <em>not</em> caught:</p> <pre data-language="pycon">>>> old_binascii.Error == binascii.Error +False +>>> try: +... old_binascii.unhexlify(b'qwertyuiop') +... except binascii.Error: +... print('boo') +... +Traceback (most recent call last): + File "<stdin>", line 2, in <module> +binascii.Error: Non-hexadecimal digit found +</pre> <p>This is expected. Notice that pure-Python modules behave the same way: it is a part of how Python works.</p> <p>The goal is to make extension modules safe at the C level, not to make hacks behave intuitively. Mutating <code>sys.modules</code> “manually” counts as a hack.</p> </section> </section> <section id="making-modules-safe-with-multiple-interpreters"> <h2>Making Modules Safe with Multiple Interpreters</h2> <section id="managing-global-state"> <h3>Managing Global State</h3> <p>Sometimes, the state associated with a Python module is not specific to that module, but to the entire process (or something else “more global” than a module). For example:</p> <ul class="simple"> <li>The <code>readline</code> module manages <em>the</em> terminal.</li> <li>A module running on a circuit board wants to control <em>the</em> on-board LED.</li> </ul> <p>In these cases, the Python module should provide <em>access</em> to the global state, rather than <em>own</em> it. If possible, write the module so that multiple copies of it can access the state independently (along with other libraries, whether for Python or other languages). If that is not possible, consider explicit locking.</p> <p>If it is necessary to use process-global state, the simplest way to avoid issues with multiple interpreters is to explicitly prevent a module from being loaded more than once per process—see <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> </section> <section id="managing-per-module-state"> <h3>Managing Per-Module State</h3> <p>To use per-module state, use <a class="reference internal" href="../c-api/module#multi-phase-initialization"><span class="std std-ref">multi-phase extension module initialization</span></a>. This signals that your module supports multiple interpreters correctly.</p> <p>Set <code>PyModuleDef.m_size</code> to a positive number to request that many bytes of storage local to the module. Usually, this will be set to the size of some module-specific <code>struct</code>, which can store all of the module’s C-level state. In particular, it is where you should put pointers to classes (including exceptions, but excluding static types) and settings (e.g. <code>csv</code>’s <a class="reference internal" href="../library/csv#csv.field_size_limit" title="csv.field_size_limit"><code>field_size_limit</code></a>) which the C code needs to function.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Another option is to store state in the module’s <code>__dict__</code>, but you must avoid crashing when users modify <code>__dict__</code> from Python code. This usually means error- and type-checking at the C level, which is easy to get wrong and hard to test sufficiently.</p> <p>However, if module state is not needed in C code, storing it in <code>__dict__</code> only is a good idea.</p> </div> <p>If the module state includes <code>PyObject</code> pointers, the module object must hold references to those objects and implement the module-level hooks <code>m_traverse</code>, <code>m_clear</code> and <code>m_free</code>. These work like <code>tp_traverse</code>, <code>tp_clear</code> and <code>tp_free</code> of a class. Adding them will require some work and make the code longer; this is the price for modules which can be unloaded cleanly.</p> <p>An example of a module with per-module state is currently available as <a class="reference external" href="https://github.com/python/cpython/blob/master/Modules/xxlimited.c">xxlimited</a>; example module initialization shown at the bottom of the file.</p> </section> <section id="opt-out-limiting-to-one-module-object-per-process"> <h3>Opt-Out: Limiting to One Module Object per Process</h3> <p>A non-negative <code>PyModuleDef.m_size</code> signals that a module supports multiple interpreters correctly. If this is not yet the case for your module, you can explicitly make your module loadable only once per process. For example:</p> <pre data-language="c">static int loaded = 0; + +static int +exec_module(PyObject* module) +{ + if (loaded) { + PyErr_SetString(PyExc_ImportError, + "cannot load module more than once per process"); + return -1; + } + loaded = 1; + // ... rest of initialization +} +</pre> </section> <section id="module-state-access-from-functions"> <h3>Module State Access from Functions</h3> <p>Accessing the state from module-level functions is straightforward. Functions get the module object as their first argument; for extracting the state, you can use <code>PyModule_GetState</code>:</p> <pre data-language="c">static PyObject * +func(PyObject *module, PyObject *args) +{ + my_struct *state = (my_struct*)PyModule_GetState(module); + if (state == NULL) { + return NULL; + } + // ... rest of logic +} +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p><code>PyModule_GetState</code> may return <code>NULL</code> without setting an exception if there is no module state, i.e. <code>PyModuleDef.m_size</code> was zero. In your own module, you’re in control of <code>m_size</code>, so this is easy to prevent.</p> </div> </section> </section> <section id="heap-types"> <h2>Heap Types</h2> <p>Traditionally, types defined in C code are <em>static</em>; that is, <code>static PyTypeObject</code> structures defined directly in code and initialized using <code>PyType_Ready()</code>.</p> <p>Such types are necessarily shared across the process. Sharing them between module objects requires paying attention to any state they own or access. To limit the possible issues, static types are immutable at the Python level: for example, you can’t set <code>str.myattribute = 123</code>.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> Sharing truly immutable objects between interpreters is fine, as long as they don’t provide access to mutable objects. However, in CPython, every Python object has a mutable implementation detail: the reference count. Changes to the refcount are guarded by the GIL. Thus, code that shares any Python objects across interpreters implicitly depends on CPython’s current, process-wide GIL.</p> </div> <p>Because they are immutable and process-global, static types cannot access “their” module state. If any method of such a type requires access to module state, the type must be converted to a <em>heap-allocated type</em>, or <em>heap type</em> for short. These correspond more closely to classes created by Python’s <code>class</code> statement.</p> <p>For new modules, using heap types by default is a good rule of thumb.</p> <section id="changing-static-types-to-heap-types"> <h3>Changing Static Types to Heap Types</h3> <p>Static types can be converted to heap types, but note that the heap type API was not designed for “lossless” conversion from static types—that is, creating a type that works exactly like a given static type. So, when rewriting the class definition in a new API, you are likely to unintentionally change a few details (e.g. pickleability or inherited slots). Always test the details that are important to you.</p> <p>Watch out for the following two points in particular (but note that this is not a comprehensive list):</p> <ul class="simple"> <li>Unlike static types, heap type objects are mutable by default. Use the <a class="reference internal" href="../c-api/typeobj#c.Py_TPFLAGS_IMMUTABLETYPE" title="Py_TPFLAGS_IMMUTABLETYPE"><code>Py_TPFLAGS_IMMUTABLETYPE</code></a> flag to prevent mutability.</li> <li>Heap types inherit <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code>tp_new</code></a> by default, so it may become possible to instantiate them from Python code. You can prevent this with the <a class="reference internal" href="../c-api/typeobj#c.Py_TPFLAGS_DISALLOW_INSTANTIATION" title="Py_TPFLAGS_DISALLOW_INSTANTIATION"><code>Py_TPFLAGS_DISALLOW_INSTANTIATION</code></a> flag.</li> </ul> </section> <section id="defining-heap-types"> <h3>Defining Heap Types</h3> <p>Heap types can be created by filling a <a class="reference internal" href="../c-api/type#c.PyType_Spec" title="PyType_Spec"><code>PyType_Spec</code></a> structure, a description or “blueprint” of a class, and calling <a class="reference internal" href="../c-api/type#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code>PyType_FromModuleAndSpec()</code></a> to construct a new class object.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Other functions, like <a class="reference internal" href="../c-api/type#c.PyType_FromSpec" title="PyType_FromSpec"><code>PyType_FromSpec()</code></a>, can also create heap types, but <a class="reference internal" href="../c-api/type#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code>PyType_FromModuleAndSpec()</code></a> associates the module with the class, allowing access to the module state from methods.</p> </div> <p>The class should generally be stored in <em>both</em> the module state (for safe access from C) and the module’s <code>__dict__</code> (for access from Python code).</p> </section> <section id="garbage-collection-protocol"> <h3>Garbage-Collection Protocol</h3> <p>Instances of heap types hold a reference to their type. This ensures that the type isn’t destroyed before all its instances are, but may result in reference cycles that need to be broken by the garbage collector.</p> <p>To avoid memory leaks, instances of heap types must implement the garbage collection protocol. That is, heap types should:</p> <ul class="simple"> <li>Have the <a class="reference internal" href="../c-api/typeobj#c.Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code>Py_TPFLAGS_HAVE_GC</code></a> flag.</li> <li>Define a traverse function using <code>Py_tp_traverse</code>, which visits the type (e.g. using <code>Py_VISIT(Py_TYPE(self))</code>).</li> </ul> <p>Please refer to the the documentation of <a class="reference internal" href="../c-api/typeobj#c.Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code>Py_TPFLAGS_HAVE_GC</code></a> and <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code>tp_traverse</code></a> for additional considerations.</p> <p>The API for defining heap types grew organically, leaving it somewhat awkward to use in its current state. The following sections will guide you through common issues.</p> <section id="tp-traverse-in-python-3-8-and-lower"> <h4> +<code>tp_traverse</code> in Python 3.8 and lower</h4> <p>The requirement to visit the type from <code>tp_traverse</code> was added in Python 3.9. If you support Python 3.8 and lower, the traverse function must <em>not</em> visit the type, so it must be more complicated:</p> <pre data-language="c">static int my_traverse(PyObject *self, visitproc visit, void *arg) +{ + if (Py_Version >= 0x03090000) { + Py_VISIT(Py_TYPE(self)); + } + return 0; +} +</pre> <p>Unfortunately, <a class="reference internal" href="../c-api/apiabiversion#c.Py_Version" title="Py_Version"><code>Py_Version</code></a> was only added in Python 3.11. As a replacement, use:</p> <ul class="simple"> <li> +<a class="reference internal" href="../c-api/apiabiversion#c.PY_VERSION_HEX" title="PY_VERSION_HEX"><code>PY_VERSION_HEX</code></a>, if not using the stable ABI, or</li> <li> +<a class="reference internal" href="../library/sys#sys.version_info" title="sys.version_info"><code>sys.version_info</code></a> (via <a class="reference internal" href="../c-api/sys#c.PySys_GetObject" title="PySys_GetObject"><code>PySys_GetObject()</code></a> and <a class="reference internal" href="../c-api/arg#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a>).</li> </ul> </section> <section id="delegating-tp-traverse"> <h4>Delegating <code>tp_traverse</code> +</h4> <p>If your traverse function delegates to the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code>tp_traverse</code></a> of its base class (or another type), ensure that <code>Py_TYPE(self)</code> is visited only once. Note that only heap type are expected to visit the type in <code>tp_traverse</code>.</p> <p>For example, if your traverse function includes:</p> <pre data-language="c">base->tp_traverse(self, visit, arg) +</pre> <p>…and <code>base</code> may be a static type, then it should also include:</p> <pre data-language="c">if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) { + // a heap type's tp_traverse already visited Py_TYPE(self) +} else { + if (Py_Version >= 0x03090000) { + Py_VISIT(Py_TYPE(self)); + } +} +</pre> <p>It is not necessary to handle the type’s reference count in <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code>tp_new</code></a> and <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code>tp_clear</code></a>.</p> </section> <section id="defining-tp-dealloc"> <h4>Defining <code>tp_dealloc</code> +</h4> <p>If your type has a custom <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code>tp_dealloc</code></a> function, it needs to:</p> <ul class="simple"> <li>call <a class="reference internal" href="../c-api/gcsupport#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code>PyObject_GC_UnTrack()</code></a> before any fields are invalidated, and</li> <li>decrement the reference count of the type.</li> </ul> <p>To keep the type valid while <code>tp_free</code> is called, the type’s refcount needs to be decremented <em>after</em> the instance is deallocated. For example:</p> <pre data-language="c">static void my_dealloc(PyObject *self) +{ + PyObject_GC_UnTrack(self); + ... + PyTypeObject *type = Py_TYPE(self); + type->tp_free(self); + Py_DECREF(type); +} +</pre> <p>The default <code>tp_dealloc</code> function does this, so if your type does <em>not</em> override <code>tp_dealloc</code> you don’t need to add it.</p> </section> <section id="not-overriding-tp-free"> <h4>Not overriding <code>tp_free</code> +</h4> <p>The <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_free" title="PyTypeObject.tp_free"><code>tp_free</code></a> slot of a heap type must be set to <a class="reference internal" href="../c-api/gcsupport#c.PyObject_GC_Del" title="PyObject_GC_Del"><code>PyObject_GC_Del()</code></a>. This is the default; do not override it.</p> </section> <section id="avoiding-pyobject-new"> <h4>Avoiding <code>PyObject_New</code> +</h4> <p>GC-tracked objects need to be allocated using GC-aware functions.</p> <p>If you use use <a class="reference internal" href="../c-api/allocation#c.PyObject_New" title="PyObject_New"><code>PyObject_New()</code></a> or <a class="reference internal" href="../c-api/allocation#c.PyObject_NewVar" title="PyObject_NewVar"><code>PyObject_NewVar()</code></a>:</p> <ul> <li> +<p>Get and call type’s <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_alloc" title="PyTypeObject.tp_alloc"><code>tp_alloc</code></a> slot, if possible. That is, replace <code>TYPE *o = PyObject_New(TYPE, typeobj)</code> with:</p> <pre data-language="c">TYPE *o = typeobj->tp_alloc(typeobj, 0); +</pre> <p>Replace <code>o = PyObject_NewVar(TYPE, typeobj, size)</code> with the same, but use size instead of the 0.</p> </li> <li> +<p>If the above is not possible (e.g. inside a custom <code>tp_alloc</code>), call <a class="reference internal" href="../c-api/gcsupport#c.PyObject_GC_New" title="PyObject_GC_New"><code>PyObject_GC_New()</code></a> or <a class="reference internal" href="../c-api/gcsupport#c.PyObject_GC_NewVar" title="PyObject_GC_NewVar"><code>PyObject_GC_NewVar()</code></a>:</p> <pre data-language="c">TYPE *o = PyObject_GC_New(TYPE, typeobj); + +TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size); +</pre> </li> </ul> </section> </section> <section id="module-state-access-from-classes"> <h3>Module State Access from Classes</h3> <p>If you have a type object defined with <a class="reference internal" href="../c-api/type#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code>PyType_FromModuleAndSpec()</code></a>, you can call <a class="reference internal" href="../c-api/type#c.PyType_GetModule" title="PyType_GetModule"><code>PyType_GetModule()</code></a> to get the associated module, and then <a class="reference internal" href="../c-api/module#c.PyModule_GetState" title="PyModule_GetState"><code>PyModule_GetState()</code></a> to get the module’s state.</p> <p>To save a some tedious error-handling boilerplate code, you can combine these two steps with <a class="reference internal" href="../c-api/type#c.PyType_GetModuleState" title="PyType_GetModuleState"><code>PyType_GetModuleState()</code></a>, resulting in:</p> <pre data-language="c">my_struct *state = (my_struct*)PyType_GetModuleState(type); +if (state == NULL) { + return NULL; +} +</pre> </section> <section id="module-state-access-from-regular-methods"> <h3>Module State Access from Regular Methods</h3> <p>Accessing the module-level state from methods of a class is somewhat more complicated, but is possible thanks to API introduced in Python 3.9. To get the state, you need to first get the <em>defining class</em>, and then get the module state from it.</p> <p>The largest roadblock is getting <em>the class a method was defined in</em>, or that method’s “defining class” for short. The defining class can have a reference to the module it is part of.</p> <p>Do not confuse the defining class with <code>Py_TYPE(self)</code>. If the method is called on a <em>subclass</em> of your type, <code>Py_TYPE(self)</code> will refer to that subclass, which may be defined in different module than yours.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The following Python code can illustrate the concept. <code>Base.get_defining_class</code> returns <code>Base</code> even if <code>type(self) == Sub</code>:</p> <pre data-language="python">class Base: + def get_type_of_self(self): + return type(self) + + def get_defining_class(self): + return __class__ + +class Sub(Base): + pass +</pre> </div> <p>For a method to get its “defining class”, it must use the <a class="reference internal" href="../c-api/structures#meth-method-meth-fastcall-meth-keywords"><span class="std std-ref">METH_METHOD | METH_FASTCALL | METH_KEYWORDS</span></a> <a class="reference internal" href="../c-api/structures#c.PyMethodDef" title="PyMethodDef"><code>calling convention</code></a> and the corresponding <a class="reference internal" href="../c-api/structures#c.PyCMethod" title="PyCMethod"><code>PyCMethod</code></a> signature:</p> <pre data-language="c">PyObject *PyCMethod( + PyObject *self, // object the method was called on + PyTypeObject *defining_class, // defining class + PyObject *const *args, // C array of arguments + Py_ssize_t nargs, // length of "args" + PyObject *kwnames) // NULL, or dict of keyword arguments +</pre> <p>Once you have the defining class, call <a class="reference internal" href="../c-api/type#c.PyType_GetModuleState" title="PyType_GetModuleState"><code>PyType_GetModuleState()</code></a> to get the state of its associated module.</p> <p>For example:</p> <pre data-language="c">static PyObject * +example_method(PyObject *self, + PyTypeObject *defining_class, + PyObject *const *args, + Py_ssize_t nargs, + PyObject *kwnames) +{ + my_struct *state = (my_struct*)PyType_GetModuleState(defining_class); + if (state == NULL) { + return NULL; + } + ... // rest of logic +} + +PyDoc_STRVAR(example_method_doc, "..."); + +static PyMethodDef my_methods[] = { + {"example_method", + (PyCFunction)(void(*)(void))example_method, + METH_METHOD|METH_FASTCALL|METH_KEYWORDS, + example_method_doc} + {NULL}, +} +</pre> </section> <section id="module-state-access-from-slot-methods-getters-and-setters"> <h3>Module State Access from Slot Methods, Getters and Setters</h3> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This is new in Python 3.11.</p> </div> <p>Slot methods—the fast C equivalents for special methods, such as <a class="reference internal" href="../c-api/typeobj#c.PyNumberMethods.nb_add" title="PyNumberMethods.nb_add"><code>nb_add</code></a> for <a class="reference internal" href="../reference/datamodel#object.__add__" title="object.__add__"><code>__add__</code></a> or <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code>tp_new</code></a> for initialization—have a very simple API that doesn’t allow passing in the defining class, unlike with <a class="reference internal" href="../c-api/structures#c.PyCMethod" title="PyCMethod"><code>PyCMethod</code></a>. The same goes for getters and setters defined with <a class="reference internal" href="../c-api/structures#c.PyGetSetDef" title="PyGetSetDef"><code>PyGetSetDef</code></a>.</p> <p>To access the module state in these cases, use the <a class="reference internal" href="../c-api/type#c.PyType_GetModuleByDef" title="PyType_GetModuleByDef"><code>PyType_GetModuleByDef()</code></a> function, and pass in the module definition. Once you have the module, call <a class="reference internal" href="../c-api/module#c.PyModule_GetState" title="PyModule_GetState"><code>PyModule_GetState()</code></a> to get the state:</p> <pre data-language="c">PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &module_def); +my_struct *state = (my_struct*)PyModule_GetState(module); +if (state == NULL) { + return NULL; +} +</pre> <p><code>PyType_GetModuleByDef()</code> works by searching the <a class="reference internal" href="../glossary#term-method-resolution-order"><span class="xref std std-term">method resolution order</span></a> (i.e. all superclasses) for the first superclass that has a corresponding module.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>In very exotic cases (inheritance chains spanning multiple modules created from the same definition), <code>PyType_GetModuleByDef()</code> might not return the module of the true defining class. However, it will always return a module with the same definition, ensuring a compatible C memory layout.</p> </div> </section> <section id="lifetime-of-the-module-state"> <h3>Lifetime of the Module State</h3> <p>When a module object is garbage-collected, its module state is freed. For each pointer to (a part of) the module state, you must hold a reference to the module object.</p> <p>Usually this is not an issue, because types created with <a class="reference internal" href="../c-api/type#c.PyType_FromModuleAndSpec" title="PyType_FromModuleAndSpec"><code>PyType_FromModuleAndSpec()</code></a>, and their instances, hold a reference to the module. However, you must be careful in reference counting when you reference module state from other places, such as callbacks for external libraries.</p> </section> </section> <section id="open-issues"> <h2>Open Issues</h2> <p>Several issues around per-module state and heap types are still open.</p> <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 mailing list</a>.</p> <section id="per-class-scope"> <h3>Per-Class Scope</h3> <p>It is currently (as of Python 3.11) not possible to attach state to individual <em>types</em> without relying on CPython implementation details (which may change in the future—perhaps, ironically, to allow a proper solution for per-class scope).</p> </section> <section id="lossless-conversion-to-heap-types"> <h3>Lossless Conversion to Heap Types</h3> <p>The heap type API was not designed for “lossless” conversion from static types; that is, creating a type that works exactly like a given static type.</p> </section> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/howto/isolating-extensions.html" class="_attribution-link">https://docs.python.org/3.12/howto/isolating-extensions.html</a> + </p> +</div> |
