-
-
Notifications
You must be signed in to change notification settings - Fork 32.2k
gh-134160: Use multi-phase init in documentation examples #134296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
8d8b366
Update docs
neonene 88c5f3f
Don't change an unrelated example
neonene a4ade5c
Apply suggestions from code review
neonene d6c42e2
ditto
neonene 97eae13
Suggested module names
neonene 8ae6bae
Avoid modernization
neonene bc78288
typo
neonene c3ab022
Correction: "error"
neonene d65303c
Rephrase warning
neonene aec6781
keywdarg_module
neonene 7dfd5ad
Update Doc/extending/extending.rst
neonene f7c72dd
Indicate xxlimited
neonene c84638c
Add seealso to index
neonene 4e59e88
Update Doc/extending/embedding.rst
neonene d68e3e3
ditto (for copy-paste)
neonene f6465bd
Shrink slots
neonene 1a65816
Remove module states
neonene a83e266
Correction: "SpamError"
neonene 2d10958
Add a Py_mod_multiple_interpreters slot
neonene a28e67c
Cancel the prvious addition as needless
neonene 9e6bff5
Merge remote-tracking branch 'upstream/main' into multi
AA-Turner d35a6b4
updates
AA-Turner 9cb3092
PEP 7
AA-Turner 6e5b1c5
revert module state for SpamError
AA-Turner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -203,31 +203,42 @@ function usually raises :c:data:`PyExc_TypeError`. If you have an argument whos | |
value must be in a particular range or must satisfy other conditions, | ||
:c:data:`PyExc_ValueError` is appropriate. | ||
|
||
You can also define a new exception that is unique to your module. For this, you | ||
usually declare a static object variable at the beginning of your file:: | ||
You can also define a new exception that is unique to your module. | ||
For this, you can declare a static global object variable at the beginning | ||
of the file:: | ||
|
||
static PyObject *SpamError; | ||
|
||
and initialize it in your module's initialization function (:c:func:`!PyInit_spam`) | ||
with an exception object:: | ||
and initialize it with an exception object in the module's | ||
:c:data:`Py_mod_exec` function (:c:func:`!spam_module_exec`):: | ||
|
||
PyMODINIT_FUNC | ||
PyInit_spam(void) | ||
static int | ||
spam_module_exec(PyObject *m) | ||
{ | ||
PyObject *m; | ||
|
||
m = PyModule_Create(&spammodule); | ||
if (m == NULL) | ||
return NULL; | ||
|
||
SpamError = PyErr_NewException("spam.error", NULL, NULL); | ||
if (PyModule_AddObjectRef(m, "error", SpamError) < 0) { | ||
Py_CLEAR(SpamError); | ||
Py_DECREF(m); | ||
return NULL; | ||
if (PyModule_AddObjectRef(m, "SpamError", SpamError) < 0) { | ||
return -1; | ||
} | ||
|
||
return m; | ||
return 0; | ||
} | ||
|
||
static PyModuleDef_Slot spam_module_slots[] = { | ||
{Py_mod_exec, spam_module_exec}, | ||
{0, NULL} | ||
}; | ||
|
||
static struct PyModuleDef spam_module = { | ||
.m_base = PyModuleDef_HEAD_INIT, | ||
.m_name = "spam", | ||
.m_size = 0, // non-negative | ||
.m_slots = spam_module_slots, | ||
}; | ||
|
||
PyMODINIT_FUNC | ||
PyInit_spam(void) | ||
{ | ||
return PyModuleDef_Init(&spam_module); | ||
} | ||
|
||
Note that the Python name for the exception object is :exc:`!spam.error`. The | ||
|
@@ -318,7 +329,7 @@ The Module's Method Table and Initialization Function | |
I promised to show how :c:func:`!spam_system` is called from Python programs. | ||
First, we need to list its name and address in a "method table":: | ||
|
||
static PyMethodDef SpamMethods[] = { | ||
static PyMethodDef spam_methods[] = { | ||
... | ||
{"system", spam_system, METH_VARARGS, | ||
"Execute a shell command."}, | ||
|
@@ -343,13 +354,10 @@ function. | |
|
||
The method table must be referenced in the module definition structure:: | ||
|
||
static struct PyModuleDef spammodule = { | ||
PyModuleDef_HEAD_INIT, | ||
"spam", /* name of module */ | ||
spam_doc, /* module documentation, may be NULL */ | ||
-1, /* size of per-interpreter state of the module, | ||
or -1 if the module keeps state in global variables. */ | ||
SpamMethods | ||
static struct PyModuleDef spam_module = { | ||
... | ||
.m_methods = spam_methods, | ||
... | ||
}; | ||
|
||
This structure, in turn, must be passed to the interpreter in the module's | ||
|
@@ -360,23 +368,17 @@ only non-\ ``static`` item defined in the module file:: | |
PyMODINIT_FUNC | ||
PyInit_spam(void) | ||
{ | ||
return PyModule_Create(&spammodule); | ||
return PyModuleDef_Init(&spam_module); | ||
} | ||
|
||
Note that :c:macro:`PyMODINIT_FUNC` declares the function as ``PyObject *`` return type, | ||
declares any special linkage declarations required by the platform, and for C++ | ||
declares the function as ``extern "C"``. | ||
|
||
When the Python program imports module :mod:`!spam` for the first time, | ||
:c:func:`!PyInit_spam` is called. (See below for comments about embedding Python.) | ||
It calls :c:func:`PyModule_Create`, which returns a module object, and | ||
inserts built-in function objects into the newly created module based upon the | ||
table (an array of :c:type:`PyMethodDef` structures) found in the module definition. | ||
:c:func:`PyModule_Create` returns a pointer to the module object | ||
that it creates. It may abort with a fatal error for | ||
certain errors, or return ``NULL`` if the module could not be initialized | ||
satisfactorily. The init function must return the module object to its caller, | ||
so that it then gets inserted into ``sys.modules``. | ||
:c:func:`!PyInit_spam` is called when each interpreter imports its module | ||
:mod:`!spam` for the first time. (See below for comments about embedding Python.) | ||
A pointer to the module definition must be returned via :c:func:`PyModuleDef_Init`, | ||
so that the import machinery can create the module and store it in ``sys.modules``. | ||
|
||
When embedding Python, the :c:func:`!PyInit_spam` function is not called | ||
automatically unless there's an entry in the :c:data:`PyImport_Inittab` table. | ||
|
@@ -433,23 +435,19 @@ optionally followed by an import of the module:: | |
|
||
.. note:: | ||
|
||
Removing entries from ``sys.modules`` or importing compiled modules into | ||
multiple interpreters within a process (or following a :c:func:`fork` without an | ||
intervening :c:func:`exec`) can create problems for some extension modules. | ||
Extension module authors should exercise caution when initializing internal data | ||
structures. | ||
If you declare a global variable or a local static one, the module may | ||
experience unintended side-effects on re-initialisation, for example when | ||
removing entries from ``sys.modules`` or importing compiled modules into | ||
multiple interpreters within a process | ||
(or following a :c:func:`fork` without an intervening :c:func:`exec`). | ||
If module state is not yet fully :ref:`isolated <isolating-extensions-howto>`, | ||
authors should consider marking the module as having no support for subinterpreters | ||
(via :c:macro:`Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED`). | ||
|
||
A more substantial example module is included in the Python source distribution | ||
as :file:`Modules/xxmodule.c`. This file may be used as a template or simply | ||
as :file:`Modules/xxlimited.c`. This file may be used as a template or simply | ||
read as an example. | ||
|
||
.. note:: | ||
|
||
Unlike our ``spam`` example, ``xxmodule`` uses *multi-phase initialization* | ||
(new in Python 3.5), where a PyModuleDef structure is returned from | ||
``PyInit_spam``, and creation of the module is left to the import machinery. | ||
For details on multi-phase initialization, see :PEP:`489`. | ||
|
||
|
||
.. _compilation: | ||
|
||
|
@@ -790,18 +788,17 @@ Philbrick ([email protected]):: | |
{NULL, NULL, 0, NULL} /* sentinel */ | ||
}; | ||
|
||
static struct PyModuleDef keywdargmodule = { | ||
PyModuleDef_HEAD_INIT, | ||
"keywdarg", | ||
NULL, | ||
-1, | ||
keywdarg_methods | ||
static struct PyModuleDef keywdarg_module = { | ||
.m_base = PyModuleDef_HEAD_INIT, | ||
.m_name = "keywdarg", | ||
.m_size = 0, | ||
.m_methods = keywdarg_methods, | ||
}; | ||
|
||
PyMODINIT_FUNC | ||
PyInit_keywdarg(void) | ||
{ | ||
return PyModule_Create(&keywdargmodule); | ||
return PyModuleDef_Init(&keywdarg_module); | ||
} | ||
|
||
|
||
|
@@ -1072,8 +1069,9 @@ why his :meth:`!__del__` methods would fail... | |
|
||
The second case of problems with a borrowed reference is a variant involving | ||
threads. Normally, multiple threads in the Python interpreter can't get in each | ||
other's way, because there is a global lock protecting Python's entire object | ||
space. However, it is possible to temporarily release this lock using the macro | ||
other's way, because there is a :term:`global lock <global interpreter lock>` | ||
protecting Python's entire object space. | ||
However, it is possible to temporarily release this lock using the macro | ||
:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using | ||
:c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to | ||
let other threads use the processor while waiting for the I/O to complete. | ||
|
@@ -1259,32 +1257,26 @@ two more lines must be added:: | |
#include "spammodule.h" | ||
|
||
The ``#define`` is used to tell the header file that it is being included in the | ||
exporting module, not a client module. Finally, the module's initialization | ||
function must take care of initializing the C API pointer array:: | ||
exporting module, not a client module. Finally, the module's :c:data:`mod_exec | ||
<Py_mod_exec>` function must take care of initializing the C API pointer array:: | ||
|
||
PyMODINIT_FUNC | ||
PyInit_spam(void) | ||
static int | ||
spam_module_exec(PyObject *m) | ||
{ | ||
PyObject *m; | ||
static void *PySpam_API[PySpam_API_pointers]; | ||
PyObject *c_api_object; | ||
|
||
m = PyModule_Create(&spammodule); | ||
if (m == NULL) | ||
return NULL; | ||
|
||
/* Initialize the C API pointer array */ | ||
PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; | ||
|
||
/* Create a Capsule containing the API pointer array's address */ | ||
c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL); | ||
|
||
if (PyModule_Add(m, "_C_API", c_api_object) < 0) { | ||
Py_DECREF(m); | ||
return NULL; | ||
return -1; | ||
} | ||
|
||
return m; | ||
return 0; | ||
} | ||
|
||
Note that ``PySpam_API`` is declared ``static``; otherwise the pointer | ||
|
@@ -1343,20 +1335,16 @@ like this:: | |
|
||
All that a client module must do in order to have access to the function | ||
:c:func:`!PySpam_System` is to call the function (or rather macro) | ||
:c:func:`!import_spam` in its initialization function:: | ||
:c:func:`!import_spam` in its :c:data:`mod_exec <Py_mod_exec>` function:: | ||
|
||
PyMODINIT_FUNC | ||
PyInit_client(void) | ||
static int | ||
client_module_exec(PyObject *m) | ||
{ | ||
PyObject *m; | ||
|
||
m = PyModule_Create(&clientmodule); | ||
if (m == NULL) | ||
return NULL; | ||
if (import_spam() < 0) | ||
return NULL; | ||
if (import_spam() < 0) { | ||
return -1; | ||
} | ||
/* additional initialization can happen here */ | ||
return m; | ||
return 0; | ||
} | ||
|
||
The main disadvantage of this approach is that the file :file:`spammodule.h` is | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not correct for multi-phase initialization, without preventing the
exec
function from other module instances from overriding this pointer.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@encukou I added but then reverted (6e5b1c5) module state for this error type -- should we un-revert that commit? Sorry for my mistake here.
A
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's fine -- module state deserves a better explanation a bit later in the tutorial. And the
ImportError
being added in the next PR is a good thing to show.The main thing I'd do differently is not backporting to 3.13 -- that's like pushing directly to production. 3.14 is out in a few months; that sounds like a good amount of time for this all to spend in prerelease.