Embeding Py: failed to instantiate a class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Brano Zarnovican

    #1

    Embeding Py: failed to instantiate a class

    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_Import Module("mod")
    cls = PyObject_GetAtt rString(module, "klass")

    ...it fails the PyClass_Check(c ls) 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(m odule, 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=PyImpo rt_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.[color=blue][color=green][color=darkred]
    >>> import mod
    >>> mod.test1[/color][/color][/color]
    <class mod.test1 at 0x4032da7c>[color=blue][color=green][color=darkred]
    >>> mod.test2[/color][/color][/color]
    <class 'mod.test2'>[color=blue][color=green][color=darkred]
    >>> mod.test1()[/color][/color][/color]
    <mod.test1 instance at 0x40337cac>[color=blue][color=green][color=darkred]
    >>> mod.test2()[/color][/color][/color]
    <mod.test2 object at 0x40337cec>[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

Working...