Difference between PyMODINIT_FUNC and PyModule_Create
Asked Answered
D

2

20

If I'm understanding correctly,

  1. PyMODINIT_FUNC in Python 2.X has been replaced by PyModule_Create in Python3.X
  2. Both return PyObject*, however, in Python 3.X, the module's initialization function MUST return the PyObject* to the module - i.e.

    PyMODINIT_FUNC
    PyInit_spam(void)
    {
       return PyModule_Create(&spammodule);
    }
    

    whereas in Python2.X, this is not necessary - i.e.

    PyMODINIT_FUNC
    initspam(void)
    {
      (void) Py_InitModule("spam", SpamMethods);
    }
    

So, my sanity checking questions are:

  • Is my understanding correct?
  • Why was this change made?

Right now, I'm only experimenting with very simple cases of C-extensions of Python. Perhaps if I were doing more, the answer to this would be obvious, or maybe if I were trying to embed Python into something else....

Disentail answered 9/5, 2012 at 3:18 Comment(0)
H
10
  1. Yes, your understanding is correct. You must return the new module object from the initing function with return type PyMODINIT_FUNC. (PyMODINIT_FUNC declares the function to return void in python2, and to return PyObject* in python3.)

  2. I can only speculate as to the motivations of the people who made the change, but I believe it was so that errors in importing the module could be more easily identified (you can return NULL from the module-init function in python3 if something went wrong).

Heighho answered 16/5, 2012 at 20:19 Comment(0)
P
1

From PEP 3121:

Entry point signature

The entry point is currently a procedure (returning void). This deviates from the usual calling conventions; callers can find out whether there was an error during initialization only by checking PyErr_Occurred. The entry point should return a PyObject*, which will be the module created, or NULL in case of an exception.

Pe answered 23/9, 2023 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.