@@ -204,31 +204,22 @@ value must be in a particular range or must satisfy other conditions,
204
204
:c:data: `PyExc_ValueError ` is appropriate.
205
205
206
206
You can also define a new exception that is unique to your module.
207
- For this, you usually declare an object variable at in the module state::
207
+ For this, you can declare a static global object variable at the beginning
208
+ of the file::
208
209
209
- typedef struct {
210
- // ...
211
- PyObject *SpamError;
212
- // ...
213
- } spam_state;
210
+ static PyObject *SpamError;
214
211
215
- and initialize it in the module's :c:data: ` Py_mod_exec ` function
216
- (:c:func: `!spam_module_exec `) with an exception object ::
212
+ and initialize it with an exception object in the module's
213
+ :c:data: ` Py_mod_exec ` function (:c:func: `!spam_module_exec `)::
217
214
218
215
static int
219
216
spam_module_exec(PyObject *m)
220
217
{
221
- spam_state *state = PyModule_GetState(m);
222
- if (state == NULL) {
223
- return -1;
224
- }
225
- state->SpamError = PyErr_NewException("spam.error", NULL, NULL);
226
- if (state->SpamError == NULL) {
227
- return -1;
228
- }
229
- if (PyModule_AddType(m, (PyTypeObject *)state->SpamError) < 0) {
218
+ SpamError = PyErr_NewException("spam.error", NULL, NULL);
219
+ if (PyModule_AddObjectRef(m, "SpamError", SpamError) < 0) {
230
220
return -1;
231
221
}
222
+
232
223
return 0;
233
224
}
234
225
@@ -240,7 +231,7 @@ and initialize it in the module's :c:data:`Py_mod_exec` function
240
231
static struct PyModuleDef spam_module = {
241
232
.m_base = PyModuleDef_HEAD_INIT,
242
233
.m_name = "spam",
243
- .m_size = sizeof(spam_state),
234
+ .m_size = 0, // non-negative
244
235
.m_slots = spam_module_slots,
245
236
};
246
237
0 commit comments