5

While following a C extension for Python tutorial, my module seems to missing its contents. While building and importing the module have no problem, using the function in the module fails. I am using Python 3.7 on macOS.

testmodule.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject* add(PyObject *self, PyObject *args) {
    const long long x, y;
    if (!PyArg_ParseTuple(args, "LL", &x, &y)) {
        return NULL;
    }
    return PyLong_FromLongLong(x + y);
}

static PyMethodDef TestMethods[] = {
    {"add", add, METH_VARARGS, "Add two numbers."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef testmodule = {
    PyModuleDef_HEAD_INIT,
    "test",
    NULL,
    -1,
    TestMethods
};

PyMODINIT_FUNC PyInit_test(void)
{
    return PyModule_Create(&testmodule);
}

setup.py

from distutils.core import setup, Extension

module1 = Extension('test', sources=['testmodule.c'])

setup(name='Test',
      version='1.0',
      description='Test package',
      ext_modules=[module1])

The test and error are

>>> import test
>>> test.add(4, 5)
AttributeError: module 'test' has no attribute 'add'
2
  • @DYZ This solved the problem. Thanks so much for pointing this error out to me. Commented Jun 5, 2019 at 2:37
  • Will post the comment as an answer for the sake of preservation. Commented Jun 5, 2019 at 2:42

1 Answer 1

2

Looks like you imported the standard module test (check test.__path__). If so, rename your module.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.