How do I make a C extension for python 3.x when a module has sub-modules? For example, I have a file called pet.c:
#include <Python.h>
PyObject* CatMeow(PyObject* self) {
return PyUnicode_FromString( ">*<" );
}
static PyMethodDef CatFunctions[] = {
{(char*) "meow", (PyCFunction) CatMeow, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}
};
static PyModuleDef CatDef = {
PyModuleDef_HEAD_INIT, "cat", "cat ext", -1, CatFunctions,
NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_cat(void) {
return PyModule_Create(&CatDef);
}
static PyModuleDef PetDef = {
PyModuleDef_HEAD_INIT, "pet", "pet ext", -1, NULL,
NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_pet(void) {
PyObject* p = PyModule_Create(&PetDef);
PyObject* c = PyInit_cat();
Py_INCREF(c);
PyModule_AddObject( p, "cat", c );
return p;
}
When I build it with the following setup.py:
from distutils.core import setup, Extension
setup(
name='pet',
version='0.0',
ext_modules=[Extension('pet', ['pet.c'])]
)
I can see
>>> import pet
>>> pet.cat.meow()
'>*<'
or
>>> from pet import cat
>>> cat.meow()
'>*<'
which is as intended, but when I try
>>> from pet.cat import meow
I have a ModuleNotFoundError saying ... No module named 'pet.cat'; 'pet' is not a package, and if I try
>>> from pet import cat
>>> from cat import meow
I have a ModuleNotFoundError saying ... No module named 'cat'. But if I check the type of cat
>>> type(cat)
<class 'module'>
which says it is a module.
How do I make this work? Adding a module object to another module used to work well in python 2.7. Is it not supposed to work in python3 due to absolute import style? Or do I have to work with multi-phase initialisation as described in PEP 489?