2

I have my extension for Python written in C. Currently I need to process in a function of my extension objects of a type declared in some external pure python module (Say, its name is ext_module). First of all I need to ensure that input object type corresponds some class from ext_module. How can I implement this? Some additional code:

static PyObject * extensionFunction( PyObject* self, PyObject *args ) {
    const char *inputString = NULL;
    PyObject *inputList = NULL;

    if ( 0 == PyArg_ParseTuple( args, "sO", &inputString, &inputList ) ) {
        return NULL;
    }

    if ( 0 != PyList_Check( inputList ) ) {
    // here I need to check whether the list items are instances of ext_module.ExtClass
    } else {
        PyErr_SetString( PyExc_TypeError, "extensionFunction: expected list" );
        return NULL;
    }
    // process arguments

    Py_RETURN_NONE;
}

Actually I can just try to call the expected methods and get an exception NotImplementedError, but I'm not sure if this is correct approach.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
Ivan
  • 588
  • 5
  • 20
  • 1
    check out http://docs.python.org/2/c-api/object.html and `PyObject_IsInstance` and `PyObject_TypeCheck`. I suspect one of those is your answer. – Adam Jun 11 '13 at 21:24
  • @Adam, I've considered that interface before asking the question, but I could not figure out how to obtain `PyTypeObject` instance of a class I want to check. – Ivan Jun 12 '13 at 05:18
  • 1
    This answer http://stackoverflow.com/a/11869355/321772 has an example for how to get `PyObject*` for a new-style class. `PyObject_IsInstance` uses a `PyObject*`. Alternatively you can hack it by making a "SetClass" C function that you call from Python that passes the class object in. – Adam Jun 12 '13 at 20:11
  • @Adam, thanks! It seems to be exactly what I want. – Ivan Jun 13 '13 at 04:23

0 Answers0