Embeding Py: failed to instantiate a class

B

Brano Zarnovican

Hi !

I need to import a module and create an instance
of a class from that module (in C).

import mod
o = mod.klass()

(mod.klass is a subclass of tuple)

When I receive a class object from the module..

module = PyImport_ImportModule("mod")
cls = PyObject_GetAttrString(module, "klass")

...it fails the PyClass_Check(cls) check.

Some classes pass the check, like:
class test1:
pass
class test3(test1):
pass

but most don't. It is enough to subclass
a buildin type. E.g. this class fails the check:
class test2(object):
pass

Q: Do I need to initialize the class object in
some way ? How ?

Thanks,

BranoZ

PS: Below are some example code used to test it.

--- mod.py ---
class test1:
pass

class test2(object):
pass

class test3(test1):
pass

--- main.c ---
#include <Python.h>

static PyObject *module = NULL;

void check(char *name) {
PyObject *cls = NULL;

printf("%s - ", name);
if ((cls=PyObject_GetAttrString(module, name)) == NULL) {
PyErr_Print();
return;
}
PyObject_Print(cls, stdout, 0);
if (!PyClass_Check(cls))
printf(" - not a class!!\n");
else
printf(" - is a class.\n");
}

int main(int argc, char *argv[]) {

Py_Initialize();

if ((module=PyImport_ImportModule("mod")) == NULL) {
PyErr_Print();
return -1;
}
check("test1");
check("test2");
check("test3");

Py_Main(argc, argv);
Py_Finalize();
}

--- output ---
$ ./main
test1 - <class mod.test1 at 0x4032da7c> - is a class.
test2 - <class 'mod.test2'> - not a class!!
test3 - <class mod.test3 at 0x4032db3c> - is a class.
Python 2.3 (#2, Feb 9 2005, 13:41:20)
[GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,144
Latest member
KetoBaseReviews
Top