Message380833
> PyModule_AddObjectRef() is just Py_XINCREF() followed by PyModule_Add(). But since most values added to the module are new references, Py_XINCREF() is usually not needed.
There is no general rule. I saw two main cases.
(A) Create an object only to add it into the module. PyModule_Add() and PyModule_AddObject() are good for that case.
Example in the array module:
PyObject *typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
if (PyModule_AddObject(m, "typecodes", typecodes) < 0) {
Py_XDECREF(typecodes);
return -1;
}
This code can be rewritten with PyModule_Add():
PyObject *typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
if (PyModule_Add(m, "typecodes", typecodes) < 0) {
return -1;
}
Py_XDECREF(typecodes) is no longer needed using PyModule_Add().
(B) Add an existing object into the module, but the objet is already stored elsewhere. PyModule_AddObjectRef() is good for that case. It became common to have this case when an object is also stored in the module state.
Example in _ast:
state->AST_type = PyType_FromSpec(&AST_type_spec);
if (!state->AST_type) {
return 0;
}
(...)
if (PyModule_AddObjectRef(m, "AST", state->AST_type) < 0) {
return -1;
}
state->AST_type and module attribute both hold a strong reference to the type. |
|
Date |
User |
Action |
Args |
2020-11-12 16:35:43 | vstinner | set | recipients:
+ vstinner, serhiy.storchaka, brandtbucher |
2020-11-12 16:35:43 | vstinner | set | messageid: <1605198943.45.0.818324639377.issue42327@roundup.psfhosted.org> |
2020-11-12 16:35:43 | vstinner | link | issue42327 messages |
2020-11-12 16:35:43 | vstinner | create | |
|