This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients brandtbucher, serhiy.storchaka, vstinner
Date 2020-11-12.16:35:43
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1605198943.45.0.818324639377.issue42327@roundup.psfhosted.org>
In-reply-to
Content
> 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.
History
Date User Action Args
2020-11-12 16:35:43vstinnersetrecipients: + vstinner, serhiy.storchaka, brandtbucher
2020-11-12 16:35:43vstinnersetmessageid: <1605198943.45.0.818324639377.issue42327@roundup.psfhosted.org>
2020-11-12 16:35:43vstinnerlinkissue42327 messages
2020-11-12 16:35:43vstinnercreate