python class in c / global calls

Thomas Grill t.grill at gmx.net
Fri Aug 23 18:44:08 CEST 2002


Hi list,
i hope you can help me with this one.
I am working on a Python scripting extension to a library for algorithmic
composition (music, that is),
therefore a have to embed the Python interpreter and steer it from within c.

I managed to implement a python class in c by following the recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54352,
which makes a new module and a dictionary and defines the methods one wants
to have. See below for more details.

Here's some python code that I execute from c:

############
import pyext
import time

print time.time()

# derive class from pyext.pybase
class testcl1(pyext.pybase):
    def fun(self):
        print "Hello"
        print time.time()

###############

Loading of the code yields no error and prints some number to the console
which corresponds to the time.
So far, so good.
Now, i construct the class "testcl1" in c and call its method "fun".
It prints "Hello" to the console, but then, the module time isn't recognized
any more!
It says:

>Traceback (most recent call last):
>File "scripts\ext1.py", line 9, in fun
>   print time.time()
>AttributeError: 'NoneType' object has no attribute 'time'


Why that? Is that some basic Python knowledge that i'm lacking?
Or is the class construction in c incomplete?
Please see the details of the c code below for reference.

many thanks for any pointers!!
Thomas

PS. Please CC: me, i am not always following the list

-----------------------------
This is the class construction code:


static PyMethodDef pyext_meths[] =
{
    {"__init__", pyext::py__init__, METH_VARARGS, "pyext init"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

static PyMethodDef pyext_mod_meths[] = {{NULL, NULL, 0, NULL}};


  PyObject *module = Py_InitModule("pyext", pyext_mod_meths);

  PyObject *moduleDict = PyModule_GetDict(module);
  PyObject *classDict = PyDict_New();
  PyObject *className = PyString_FromString("pybase");

  PyObject *fooClass = PyClass_New(NULL, classDict, className);
  PyDict_SetItemString(moduleDict, "pybase", fooClass);
  Py_DECREF(classDict);
  Py_DECREF(className);
  Py_DECREF(fooClass);

  // add methods to class
  for (PyMethodDef *def = pyext_meths; def->ml_name != NULL; def++) {
   PyObject *func = PyCFunction_New(def, NULL);
   PyObject *method = PyMethod_New(func, NULL, fooClass);
   PyDict_SetItemString(classDict, def->ml_name, method);
   Py_DECREF(func);
   Py_DECREF(method);
  }








More information about the Python-list mailing list