@@ -1206,6 +1206,68 @@ type for ``self``, it's best to create your own converter, subclassing
12061206 [clinic start generated code]*/
12071207
12081208
1209+ Using a "defining class" converter
1210+ ----------------------------------
1211+
1212+ Argument Clinic facilitates gaining access to the defining class of a method.
1213+ This is useful for :ref: `heap type <heap-types >` methods that need to fetch
1214+ module level state. Use :c:func: `PyType_FromModuleAndSpec ` to associate a new
1215+ heap type with a module. You can now use :c:func: `PyType_GetModuleState ` on
1216+ the defining class to fetch the module state, for example from a module method.
1217+
1218+ Example from ``Modules/zlibmodule.c ``. First, ``defining_class `` is added to
1219+ the clinic input::
1220+
1221+ /*[clinic input]
1222+ zlib.Compress.compress
1223+
1224+ cls: defining_class
1225+ data: Py_buffer
1226+ Binary data to be compressed.
1227+ /
1228+
1229+
1230+ After running the Argument Clinic tool, the following function signature is
1231+ generated::
1232+
1233+ /*[clinic start generated code]*/
1234+ static PyObject *
1235+ zlib_Compress_compress_impl(compobject *self, PyTypeObject *cls,
1236+ Py_buffer *data)
1237+ /*[clinic end generated code: output=6731b3f0ff357ca6 input=04d00f65ab01d260]*/
1238+
1239+
1240+ The following code can now use ``PyType_GetModuleState(cls) `` to fetch the
1241+ module state::
1242+
1243+ zlibstate *state = PyType_GetModuleState(cls);
1244+
1245+
1246+ Each method may only have one argument using this converter, and it must appear
1247+ after ``self ``, or, if ``self `` is not used, as the first argument. The argument
1248+ will be of type ``PyTypeObject * ``. The argument will not appear in the
1249+ ``__text_signature__ ``.
1250+
1251+ The ``defining_class `` converter is not compatible with ``__init__ `` and ``__new__ ``
1252+ methods, which cannot use the ``METH_METHOD `` convention.
1253+
1254+ It is not possible to use ``defining_class `` with slot methods. In order to
1255+ fetch the module state from such methods, use ``_PyType_GetModuleByDef `` to
1256+ look up the module and then :c:func: `PyModule_GetState ` to fetch the module
1257+ state. Example from the ``setattro `` slot method in
1258+ ``Modules/_threadmodule.c ``::
1259+
1260+ static int
1261+ local_setattro(localobject *self, PyObject *name, PyObject *v)
1262+ {
1263+ PyObject *module = _PyType_GetModuleByDef(Py_TYPE(self), &thread_module);
1264+ thread_module_state *state = get_thread_state(module);
1265+ ...
1266+ }
1267+
1268+
1269+ See also :pep: `573 `.
1270+
12091271
12101272Writing a custom converter
12111273--------------------------
0 commit comments