Skip to content

Updating Python modules in C for Python3 #7

@arunppsg

Description

@arunppsg

The post on Python modules in C is one of the best introductory post which I have ever seen on that topic. It will be great if it could be updated to work with Python3. To make it work, we need to do the following changes:

  • Use PyModuleDef to define the module in _chi2.c
static PyModuleDef chi2_module = {
    PyModuleDef_HEAD_INIT,
    .m_name = "_chi2",
    .m_doc = module_docstring,
    .m_size = -1,
    .m_methods = module_methods,
};
  • Use PyInit__chi2 instead of init_chi2, update the function to return NULL when the module does not get initialized and PyModule_Create instead of Py_InitModule3. The updated version:
PyMODINIT_FUNC PyInit__chi2(void)
{ 
  PyObject *m = PyModule_Create(&chi2_module);
  if (m == NULL) {
    return NULL; 
  }
  
  /* Load numpy functionality */
  import_array();

  return m;
}

Thank you for the wonderful post.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions